Consider the TypeScript code snippet below:
const namesList = {
john: 25,
emma: 30,
jacob: 35,
}
type NameType = keyof typeof namesList
function getPersonAge<
Name extends string,
Result = Name extends NameType
? number
: string extends Name
? (number | null)
: null
>(nameInput: Name): Result {
return (namesList[nameInput as NameType] ?? null) as Result
}
The conditional return type of getPersonAge
leads to different types for various cases:
getPersonAge('john') // case 1, returns `number`
getPersonAge('lily') // case 2, returns `null`
getPersonAge(prompt('Enter your name:') ?? '') // case 3, returns `number | null`
The goal is to prevent case 2 from being allowed at compile time. Only a valid name or a dynamically entered string should be accepted, while an invalid literal name should result in a type-check error.
Is it achievable?