简体   繁体   English

是否可以在打字稿的对象中使用泛型?

[英]is it possible to use generics in an object in typescript?

I'm trying to set the type of one object value based on the type of another value and I'm curious if this is possible.我正在尝试根据另一个值的类型设置一个对象值的类型,我很好奇这是否可能。 Given:鉴于:

type KeyType = 'string' | 'number'
type ValueType = { string: string, number: number }

type TestObject<T extends KeyType> = {
  key: T
  args: ValueType[T]
}

const test1: TestObject = { key: 'string', value: 'hello' } // should be ok
const test2: TestObject = { key: 'number', value: 2 } // should be ok
const test3: TestObject = { key: 'string', value: 2 } // should fail, value should be string

is there a way to do this in typescript?有没有办法在打字稿中做到这一点? I can only get this to work if I pass the generic to the type declaration.如果我将泛型传递给类型声明,我只能让它工作。 However I know in functions its possible for this to be inferred.但是我知道在函数中可以推断出这一点。

is it possible to use generics in an object in typescript?是否可以在打字稿的对象中使用泛型?

Yes.是的。 Here is the working code (you were close):这是工作代码(你很接近):

export type KeyType = 'string' | 'number'
type ValueType = { string: string, number: number }

type TestObject<T extends KeyType> = {
  key: T
  value: ValueType[T]
}

const testA: TestObject<'string'> = { key: 'string', value: 'hello' } // should be ok
const testB: TestObject<'number'> = { key: 'number', value: 2 } // should be ok
const testC: TestObject<'string'> = { key: 'string', value: 2 } // Error: value needs to be string

Showing the error:显示错误: 在此处输入图片说明

More更多的

You need to specify the generic when using a generic as a type annotation eg TestObject<'number'>使用泛型作为类型注释时需要指定泛型,例如TestObject<'number'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM