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 ?
CodePudding user response:
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. 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. It covers all of the basics in a very concise way.