#Mapped types

16 messages · Page 1 of 1 (latest)

gritty lintel
#

#ts-discussion message

stiff cloud
#

👋

gritty lintel
#

Hey,

stiff cloud
#

a question to help me answer your last question: have you seen as const before?

gritty lintel
#
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?

stiff cloud
#

(just the "Literal Inference" section i mean)

#

(though really the whole handbook is worth a read at some point)

gritty lintel
#

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 }
stiff cloud
#

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

gritty lintel
#

Cool! Thanks for your help