如何定义Typescript中的对象类型?

时间:2017-07-13 14:42:57

标签: typescript

我有以下代码:

type Machine = {
    id: string,
    name: string,
    tonnage?: number
}

const machines = {
    "machine1": {id: "S01", name: "AnyMachine"} as Machine,
}

可以指示键是字符串,值是机器类型吗? Casting as Machine似乎有效,但我希望有更简洁的替代方案。

2 个答案:

答案 0 :(得分:2)

您可以这样做:

interface MachineHolder {
  [key: string]: Machine;
}

type Machine = {
  id: string,
  name: string,
  tonnage?: number
}

const machines: MachineHolder = {
  "machine1": {id: "S01", name: "AnyMachine"},
}

答案 1 :(得分:2)

你可以这样做:

type Machines = {
    [key: string]: Machine;
}

const machines: Machines = {
    "machine1": { id: "S01", name: "AnyMachine" }
}

但是,根据您尝试做的事情,可能没有必要 Typescript类型系统是based on the structure of the types,所以你可以这样做,它将起作用:

const machines = {
    "machine1": { id: "S01", name: "AnyMachine" }
}

function fn(machine: Machine) {
    // ...
}

fn(machines.machine1);

虽然machines未定义为Machine s的地图,但编译器会推断您正在传递正确的类型。