Last active
July 13, 2022 16:20
-
-
Save gosseti/c2bf95666ff6fe27c8849cd60f0d1a7d to your computer and use it in GitHub Desktop.
TypeScript Question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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