Skip to content

Instantly share code, notes, and snippets.

@gosseti
Last active July 13, 2022 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gosseti/c2bf95666ff6fe27c8849cd60f0d1a7d to your computer and use it in GitHub Desktop.
Save gosseti/c2bf95666ff6fe27c8849cd60f0d1a7d to your computer and use it in GitHub Desktop.
TypeScript Question
// when T is a custom type we want to infer from
// that rather than extending from any string
export function isValueInArray<T extends string>(
values: T[],
value: T | undefined
) {
return value ? values.includes(value) : false;
}
type Status = 'PENDING' | 'ERROR' | 'SUCCESS';
type Props = {
status: Status;
};
function Component(props: Props) {
// this should throw a type erorr because "TEST" isn’t a valid Status
// the reason it works is because isValueInArray<T extends string>
// so any string is valid
const isValidValue = isValueInArray(['PENDING', 'TEST'], props.status);
return isValidValue ? <div>Valid</div> : <div>Invalid</div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment