#Mapped types
16 messages · Page 1 of 1 (latest)
👋
Hey,
a question to help me answer your last question: have you seen as const before?
type TypeNameToType = {
string: string
number: number
}
type MapTypeNamesToTypes<T extends Record<PropertyKey, keyof TypeNameToType>> = {
[K in keyof T]: TypeNameToType[T[K]]
}
const x = {"a": "string", "b": "number"} as const
type Blah = MapTypeNamesToTypes<typeof x>
// ^? - type Blah = {
// readonly a: string;
// readonly b: number;
// }
Nope never before
What does it do?
maybe give this section of the handbook a read, it can probably explain this stuff better than me: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-inference
The language primitives.
(just the "Literal Inference" section i mean)
(though really the whole handbook is worth a read at some point)
Mhmm okay i get it
How about using such in a generic function for example tho, where the object to infer is a function argument?
function mapper<T extends Record<PropertyKey, keyof TypeNameToType>(schema: T): MapTypeNamesToTypes<typeof schema> {
...
}
Does this work if i just pass an object using the as const suffix?
const r = mapper({a:"string",b:"number"} as const)
// - typeof r = { a: string, b: number }
yep, you got it
TS 5.0 will have a const modifier you can use to infer it that way by default. you'd write this:
function mapper<const T extends Record<PropertyKey, keyof TypeNameToType>(schema: T): MapTypeNamesToTypes<typeof schema> {
...
}
then you won't need as const at the call site
Cool! Thanks for your help