简体   繁体   English

TypeScript接口和动态键

[英]TypeScript interfaces and dynamic keys

I hope it can be done.我希望它可以做到。

The condition is simple - I have 2 types.条件很简单——我有两种类型。

type Numbers: Number[];
type Name: string;

Let's say they represent data I retrieved somewhere:假设它们代表我在某处检索到的数据:

// first provider sends it like this
{ "numbers": [2, 3, 4], "name": "Mike" }

// second uses different API keys, even though the data type is the same
{ "numeros": [ 7, 8 ], "nombre": "Jose" }

I have no idea how API creators named their properties, I just know that the returned payload will have 2 different properties - one with Numbers and another with Name .我不知道 API 创建者如何命名他们的属性,我只知道返回的有效负载将具有 2 个不同的属性 - 一个带有Numbers ,另一个带有Name

interface INumbers {
    [propName: string]: Numbers
}

interface INames {
    [propName: string]: Names
}

I know that index signature is used in cases when property name is unknown.我知道在属性名称未知的情况下使用索引签名。 It also specifies that there might be more than 1 property.它还指定可能有超过 1 个属性。 What I'm trying to figure out is if it's possible to join INumbers and INames together.我想弄清楚的是是否可以将INumbersINames连接在一起。

I've tried union types, but then the object that implements this interface might have only 1 property.我尝试过联合类型,但是实现此接口的 object 可能只有 1 个属性。 Another idea to extend interfaces did not work as well.扩展接口的另一个想法也没有奏效。

interface IPayload {
    [propName: string]: INumbers | INames
}

// this will use `[propName: string]` from 1st extended interface, ignoring others
interface IPayload extends INumbers, INames {}

I wonder if it's even can be done.我想知道它是否甚至可以完成。 Will appreciate any help.将不胜感激任何帮助。

Thanks!谢谢!

type NumberListType = Number[];
type NameType = string;

type NumberKeyType = "numbers" | "numeros";
type NameKeyType = "name" | "nombre";

type INumbers = {
  [propName in NumberKeyType]: NumberListType;
};

type INames = {
  [propName in NameKeyType]: NameType;
};

interface IPayload extends Partial<INames>, Partial<INumbers> {}

const pay: IPayload = {
  numeros: [1, 2],
  name: "",
  // numbers: "", Error
  // nombre: [1, 2], Error
};

I try it, It is right you want?我试试看,你想要的对吗? Thanks.谢谢。

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

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