如何在Typescript中将基本类型分配给变量?

时间:2018-12-04 12:46:48

标签: typescript

我具有数据表中列的表示形式,例如:

[
  {prop: "firstName", header: "First name"},
  {prop: "birthday", header: "Birthday"},
  {prop: "amountInAccount", header: "Amount in account"}
]

,一行如下所示:

{
  firstName: "John",
  birthday: 1543926555,
  amountInAccount: "1000"
}

根据每列的类型,我想在我的UI中显示一个不同的小部件。我想将类型定义存储在column接口中,而不使用类型的枚举。

我已经尝试过了:

interface IColumn {
  prop: string;
  header: string;
  type: typeof string | typeof number | typeof Date;
}

所以我可以这样声明我的专栏:

[
  {prop: "firstName", header: "First name", type: string},
  {prop: "birthday", header: "Birthday", type: Date},
  {prop: "amountInAccount", header: "Amount in account", type: number}
]

但由于error TS2693: 'string' only refers to a type, but is being used as a value here

而无法使用

如何在不使用枚举或存储字符串"string""number"或“ Date”的情况下正确实现我的想法?

1 个答案:

答案 0 :(得分:2)

您可以创建一个表示原始值的字符串值的自定义类型库

type primitive = 'string' | 'number' | 'date';

interface IColumn {
  prop: string;
  header: string;
  type: primitive;
}

这应该有效

[
  {prop: "firstName", header: "First name", type: 'string'},
  {prop: "birthday", header: "Birthday", type: 'date'},
  {prop: "amountInAccount", header: "Amount in account", type: 'number'}
]

使用数字和字符串构造函数的另一种方法

interface IColumn {
  prop: string;
  header: string;
  type: typeof String | typeof Number |  typeof Date;
}

const data : IColumn[] =  [
      {prop: "firstName", header: "First name", type: String},
      {prop: "birthday", header: "Birthday", type: Date},
      {prop: "amountInAccount", header: "Amount in account", type: Number }
    ]

 console.log(data.filter( i => i.type == Number))
相关问题