Typescript接口属性作为通用对象的嵌套键

问题描述 投票:0回答:1

基于以下结构:

interface ApiEntity {
  [key: string]: number | string;
}

interface ApiData {
  [key: string]: ApiEntity;
}

interface Entity1 extends ApiEntity {
  id: number;
  name: string;
}

interface Entity2 extends ApiEntity {
  uuid: string;
  description: string;
}

interface MyData extends ApiData {
  a: Entity1;
  b: Entity2;
}

如何创建仅接受有效实体和属性的接口:

// The problem
interface DataFields<T extends ApiData> {
  label: string;
  entity: keyof T; // ensure that entity is one of the properites of abstract ApiData
  property: keyof keyof T; // ensure that property is one of the properties of ApiEntity
  other?: string;
}

因此,创建的字段是安全的,并且TS无效时会显示错误:

const fields: MyDataFields<MyData>[] = [{
  label: 'A ID',
  entity: 'a', // valid
  property: 'id', // valid
},{
  label: 'B Description',
  entity: 'b', // valid
  property: 'description', // valid
},{
  label: 'Invalid',
  entity: 'c', // TS Error
  property: 'name', // TS Error
}];

甚至更好:

const MyDataFields: DataField<MyData>[] = [
  {label: 'A ID', entityProperty: 'a.id'},
  {label: 'B Description', entityProperty: 'b.description'},
  {label: 'Invalid', entityProperty: 'c.name'}, // TS Error
];
typescript typescript-generics
1个回答
0
投票

使用您已定义的接口层次结构,其中将ApiDataApiEntity声明为允许任何字符串作为属性名称,Typescript根本无法推断c不是MyData的有效属性名称,或者name不是Entity2的有效属性名称。相反,由于接口的声明方式,Typescript会推断出这些are有效属性名称:

function foo(obj: Entity1): void {
  // no type error
  console.log(obj.foo);
}
function bar(obj: MyData): void {
  // no type error
  console.log(obj.bar);
}

但是如果您摆脱了ApiDataApiEntity,或者至少缩小它们的范围以不允许所有字符串作为属性名称,则可以解决此问题。

property的有效值取决于entity的值,因此这必须是已区分的联合类型,其中entity是判别式。我们可以使用映射类型来构造它:

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

interface Entity2 {
  uuid: string;
  description: string;
}

interface MyData {
  a: Entity1;
  b: Entity2;
}

type DataFields<T> = {
  [K in keyof T]: {
    label: string,
    entity: K,
    property: keyof (T[K])
  }
}[keyof T]

示例:

const fields: DataFields<MyData>[] = [{
  label: 'A ID',
  entity: 'a', // OK
  property: 'id', // OK
}, {
  label: 'B Description',
  entity: 'b', // OK
  property: 'description', // OK
}, {
  label: 'Invalid',
  // Type error: 'c' is not assignable to 'a' | 'b'
  entity: 'c',
  property: 'name',
}, {
  label: 'Invalid',
  entity: 'a',
  // Type error: 'foo' is not assignable to 'id' | 'name' | 'uuid' | 'description'
  property: 'foo',
},
// Type error: 'id' is not assignable to 'uuid' | 'description'
{
  label: 'Invalid',
  entity: 'b',
  property: 'id',
}];

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.