![](/img/trans.png)
[英]How to define a conditional return type based on if an object property is set in Typescript
[英]typescript : how to define type for object property?
通常,您通過為整個對象定義一個類型(如您的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 手冊值得從頭到尾閱讀。 它以非常簡潔的方式涵蓋了所有基礎知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.