Typescript: An index signature parameter type cannot be a literal type or generic type

2.2k views Asked by At

I am trying to create a simple typescript program,

which constraints an object to match a given interface data type.

For example, I have an interface Config and a schema object

I want abc.value to be restricted as string while xyz.value to be restricted as number:

interface Config {
  abc: string
  xyz: number
}

const schema: XXX = {
  abc: {
    value: '',
  },
  xyz: {
    value: 0,
  },
}

I tried using infer keyword but cannot get it work properly.

const schema: Record<T extends keyof Config ? infer keyof Config : any, any> = {
  abc: {
    value: '',
  },
  xyz: {
    value: 0,
  },
}

what I doing wrong here? Any help would be appreciated

Thank you.

1

There are 1 answers

1
captain-yossarian from Ukraine On BEST ANSWER

Please use mapped types:

interface Config {
    abc: string
    xyz: number
}

type Mapped<T> = {
    [Prop in keyof T]: {
        value: T[Prop]
    }
}

const schema: Mapped<Config> = {
    abc: {
        value: '2',
    },
    xyz: {
        value: 0,
    },
}

Playground