我正在学习打字稿,为什么定义数组在这里显示错误?

时间:2019-06-21 10:15:59

标签: arrays typescript

我正在学习打字稿 为什么定义数组的地方显示错误? //尝试过(字符串|数字)[]

interface IState {
  orgTypes: Array<orgTypes>;  //shows error here

  orgType: string;
}

const data: IState = {
  orgType: "",

  orgTypes: [
    { id: "1", name: "Vendor" },
    { id: "2", name: "Supplier" },
    { id: "3", name: "Vendor and Supplier" }
  ]
};

2 个答案:

答案 0 :(得分:1)

您没有在任何地方定义名为orgTypes的类型。从问题和评论中,我怀疑您想要这样的东西:

// Define an `OrgType` type
interface OrgType {
    id: string;
    name: string;
}

// Define an `IState` type
interface IState {
  orgTypes: OrgType[]; // Or Array<OrgType>; if you prefer, same thing
  orgType: string;
}

// Define runtime data using those types
const data: IState = {
  orgType: "",

  orgTypes: [
    { id: "1", name: "Vendor" },
    { id: "2", name: "Supplier" },
    { id: "3", name: "Vendor and Supplier" }
  ]
};

(在playground上)

如果您不想为OrgType定义实际的接口,也可以内联:

// Define an `IState` type
interface IState {
  orgTypes: {id: string; name: string;}[];
  orgType: string;
}

// Define runtime data using those types
const data: IState = {
  orgType: "",

  orgTypes: [
    { id: "1", name: "Vendor" },
    { id: "2", name: "Supplier" },
    { id: "3", name: "Vendor and Supplier" }
  ]
};

(在playground上)

但是几乎在任何时候我看到有人定义这样的内联时,他们最终在其他地方再次需要它,所以...

答案 1 :(得分:0)

没有类型orgTypes,您已将其声明为变量名。我猜你想声明一个你喜欢的类型

type orgs = {id: string, name: string}

interface IState {
  orgTypes: Array<orgs>;

  orgType: string;
}