打字稿试图推断对象的泛型

时间:2018-09-26 07:50:03

标签: typescript typescript-generics

这是我要完成的工作,但对于具有泛型的对象。 Is there a `valueof` similar to `keyof` in TypeScript?

// Something on this lines. I know this is not supported but i am trying to convey the idea here.

type payload<T> = <K extends keyof T>{prop: K, value: T[K]};

const someObj = {a: string, b: number};

type someObjType = payload<someObj>;

const someObjPayload: someObjType = { prop: 'a', value: 'some string'} // should work.

const someObjPayload: someObjType = { prop: 'a', value: 200 } // should throw an error.

2 个答案:

答案 0 :(得分:1)

由于TypeScript只允许numberstring,所以只写两次就更简单了-不用输入类型参数K

type stringKeyPayload<T> = {prop: string, value: T}
type numberKeyPayload<T> = {prop: number, value: T}

答案 1 :(得分:1)

不幸的是,打字稿不允许部分推断变量。如果要确保该值与key指定的属性具有相同的类型,则将需要使用helper函数来获得适当的推断行为:

type payload<T, K extends keyof T> = {prop: K, value: T[K]};

let someObj!: {a: string, b: number};

function getProp<K extends keyof typeof someObj>(o: payload<typeof someObj, K>) {
  return o
}

const someObjPayload = getProp({ prop: 'a', value: 'some string'}) // ok of type payload<{ a: string; b: number; }, "a">

const someObjPayload2= getProp({prop: 'a', value: 100}) // error