3π
β
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.
π€T.J. Crowder
Source:stackexchange.com