【问题标题】:typescript : how to define type for object property?打字稿:如何定义对象属性的类型?
【发布时间】:2021-12-16 18:52:36
【问题描述】:

我的组件中有这个对象

其中一个属性具有类型

interface IProduct {
  artikelname: string
  artikelnummer: string
  barccode: string
}

  form = {
    date: [],
    R2Os: [],
    type: 1,
    cats: null,
    selected_product: Array<IProduct>
  }

但我认为这种打字的方式不是true

我有错误

那么,我怎样才能为 Object Property 定义 type

【问题讨论】:

  • form = { ... } 创建一个对象,你的对象字面量必须是一个值,而不是 type。您可以在 =form: { ... } = { ... } 左侧或在单独的 type 规范中指定类型。

标签: typescript vue.js


【解决方案1】:

通常,您通过为整个对象定义一个类型(如您的IProduct)并在声明它时将该类型分配给引用该对象的变量(form)来实现。例如:

interface FormType {
    date: Array<something>;
    R20s: Array<something>;
    type: number;
    cats: null | something;
    selected_product: Array<IProduct>;
}
// ...
const form: FormType = {
//        ^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− giving type to object
    date: [],
    R2Os: [],
    type: 1,
    cats: null,
    selected_product: [],
    //                ^^−−−−−−−−−−−−−−−−−−−−−−−−− value
};

但您也可以使用内联类型断言来做到这一点:

const form = {
    date: [],
    R2Os: [],
    type: 1,
    cats: null,
    //                vv−−−−−−−−−−−−−−−−−−−−−−−−− value
    selected_product: [] as Array<IProduct>,
    //                  ^^^^^^^^^^^^^^^^^^^−−−−−− type assertion
};

TypeScript handbook 从头到尾都值得一读。它以非常简洁的方式涵盖了所有基础知识。

【讨论】:

    猜你喜欢
    • 2018-08-21
    • 2018-01-18
    • 2020-10-06
    • 2021-12-06
    • 2019-06-15
    • 2017-09-06
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多