Issue
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}?
Solution
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}
Answered By - Oblosys
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.