繁体   English   中英

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

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

我正在尝试根据另一个值的类型设置一个对象值的类型,我很好奇这是否可能。 鉴于:

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

有没有办法在打字稿中做到这一点? 如果我将泛型传递给类型声明,我只能让它工作。 但是我知道在函数中可以推断出这一点。

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

是的。 这是工作代码(你很接近):

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

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

更多的

使用泛型作为类型注释时需要指定泛型,例如TestObject<'number'>

暂无
暂无

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

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