Suppose we have the following enum
enum PrimayValType {
"string",
"boolean",
"integer",
"float"
}
Now i want to write a function that inputs a Buffer and a parameter of type PrimaryValType and converts the buffer based on the PrimaryValType. How to write such a function in Typescript?
function f(b: Buffer, t: PrimayValType): ??? {
// converts b to a literal based on t
}
const b = Buffer.from('test', 'utf-8');
f(b, PrimayValType.string) // should be of type string
You can write the return type of your function as a mapped type. First, define
PrimaryValTypeas a mapping from the string literals to the actual types:Then given a string of type
K extends keyof PrimaryValType, we can map it to the correct return type using the mapped typePrimaryValType[K].To parse the input as the right type, you can switch on the type-string:
The type assertions are needed because Typescript can't tell that when
t === 'integer'thenKcan't be'string', for example. The code can be neatened by storing the parser functions in an object, as in @kmos.w's answer:The type assertion is still needed, for the same reason.
Playground Link