如何在接口中定义字符串数组?

时间:2019-03-30 07:34:05

标签: typescript

我尝试过:

export interface ITarifFeatures {
  key: string;
}


export interface ITarif {
   features: ITarifFeatures[];
}

然后我基于接口创建对象:

let obj<ITarif> {
      name: "Базовый",
      description: "Подходит для...",
      currency: "A",
      price: 1.99,
      period: "Месяц",
      features: ["СМС уведомления"]
    };

但是此属性是错误的:

features: ["СМС уведомления"]

我也尝试过:

export type ITarifFeatures = {
  key: string[];
}

export interface ITarif {
  name: string;
  description: string;
  currency: string;
  price: number;
  period: string;
  features: ITarifFeatures
}

2 个答案:

答案 0 :(得分:1)

interface类型ITarifFeatures期望您没有提供名为key的属性,您正在数组中传递string类型["СМС уведомления"]的实例而是将代码修改为此:

export interface ITarifFeatures {
  key: string;
}
export interface ITarif {
    features: ITarifFeatures[];
    [x: string]: any 
}

let itarif: ITarifFeatures = {key: "СМС уведомления"};
let obj: ITarif = {
      name: "Базовый",
      description: "Подходит для...",
      currency: "A",
      price: 1.99,
      period: "Месяц",
      features: [itarif]
};

此外,ITarif类型将仅接受features属性,但是您正在尝试为其提供更多键值。要绕开它,请添加一个 indexer [x: string]: any  在原始界面中。

答案 1 :(得分:1)

字符串类型!= ITarifFeatures

需要的是这样的对象:

{
    key:'blabla'
}