可以在typescript中的对象中使用泛型吗?

可以在typescript中的对象中使用泛型吗?,typescript,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', valu

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

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
type KeyType='string'|'number'
类型ValueType={string:string,number:number}
类型TestObject={
关键词:T
args:ValueType[T]
}
const test1:TestObject={key:'string',value:'hello'}//应该可以
const test2:TestObject={key:'number',value:2}//应该是正常的
const test3:TestObject={key:'string',value:2}//应失败,值应为string
有没有办法在typescript中实现这一点?只有将泛型传递给类型声明,我才能使其工作。然而,我知道在函数中可以推断出这一点

可以在typescript中的对象中使用泛型吗

对。以下是工作代码(您很接近):

导出类型KeyType='string'|'number'
类型ValueType={string:string,number:number}
类型TestObject={
关键词:T
值:ValueType[T]
}
const testA:TestObject={key:'string',value:'hello'}//应该是正常的
const testB:TestObject={key:'number',value:2}//应该是正常的
const testC:TestObject={key:'string',value:2}//错误:value需要是string
显示错误:

更多 使用泛型作为类型注释时,需要指定泛型,例如
TestObject

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