Home > Blockchain >  How to create your own type based on function parameters?
How to create your own type based on function parameters?

Time:09-08

Let's say there is a function to create an object.

interface Params {
  name: string
}

const createTypedObject = (params: Params) => ({
  [params.name]: 1,
})

I create an object

const obj = createTypedObject({ name: 'test' })
// Type obj {[p: string]: number}

How to make object type be {test: number}?

CodePudding user response:

TypeScript isn't great at inferring generic types from created objects, so you're going to have to use a type assertion:

const createTypedObject = <P extends Params>(params: P) => ({
  [params.name]: 1,
}) as {[K in P['name']]: number}

Also note that the type of object literal {name: 'test'} is {name: string}, so to get the correctly narrowed property type, you'll have to add an as const to the parameter:

const obj = createTypedObject({name: 'test'} as const)
// obj: {test: number}

Alternatively, you can make params readonly, which will let TypeScript infer the narrowed type for literal objects, even without as const:

const createTypedObject = <P extends Params>(params: Readonly<P>) => ({
  [params.name]: 1,
}) as {[K in P['name']]: number}

const obj = createTypedObject({name: 'test'})
//    obj: {test: number}

TypeScript playground

  • Related