打字稿钥匙,根据钥匙数量改变类型

时间:2020-01-24 07:07:42

标签: typescript

我有一个公开接口的库。我正在使用keyof功能向函数参数添加类型。默认情况下,该接口为空。 用户可以扩展此界面(模块扩展)

如果界面不包含任何键,是否可以将类型更改为any

interface A {}

function test(a: keyof A) {}


test('anyType') // here it should be `any`

interface A {
  id: number;
  name: string;
}

function test(a: keyof A) {}


test('name') // here it should be `id | name`

1 个答案:

答案 0 :(得分:3)

如果export class DeviceInput { ID: number; constructor(_id:number) { this.ID = _id; } } export class Reprocess { Flag: boolean; ProductID: number; DeviceIds: DeviceInput[] = []; } 不具有属性this.reprobj.DeviceIds.push(new DeviceInput(someId)); ,则解析为A。因此,您可以在此处使用Conditional Types,例如:

keyof A

Playground link

相关问题