简体   繁体   English

打字稿:如何定义对象属性的类型?

[英]typescript : how to define type for object property?

I have this object in my component我的组件中有这个对象

one of its Property has type它的属性之一具有类型

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

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

but I think this way of typing is not true但我认为这种打字方式不正确

and i have error ,我有错误

在此处输入图片说明

so, how Can I define type for Object Property ?那么,如何为Object Property定义类型

Normally, you do it by defining a type (like your IProduct ) for the object as a whole, and assigning that type to the variable referring to the object ( form ) when you declare it.通常,您通过为整个对象定义一个类型(如您的IProduct ),并在声明它时将该类型分配给引用该对象( form )的变量来实现。 For instance:例如:

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
};

but you can also do it with an inline type assertion:但您也可以使用内联类型断言来做到这一点:

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

The TypeScript handbook is worth reading from beginning to end. TypeScript 手册值得从头到尾阅读。 It covers all of the basics in a very concise way.它以非常简洁的方式涵盖了所有基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM