[英]How to enforce object type with interface property - value
我有這個界面
interface SUser {
ID: number;
NAME: string;
MAIL: string;
PASSWORD: string;
GENDER: number;
BIRTHDATE: string;
ID_FB: string;
CREDIT: number;
ID_REFERRAL: number;
}
而且我想要一種描述對象的類型,並確保我的對象與我的接口屬性之一的鍵和值匹配。
我嘗試了以下方法:
type fieldType = { [K in SUser]: string | number };
我將字段對象設置為僅允許來自SUser
的鍵,但例如,如果鍵的值是ID
,則將值設置為字符串,則想得到一個錯誤。
基本上,我想基於我的界面強制執行鍵-值對。
使用前面的代碼,我得到以下錯誤,並且不強制使用值類型:
Type 'SUser' is not assignable to type 'string | number | symbol'.
Type 'SUser' is not assignable to type 'symbol'.
在這個問題上有幫助嗎?
你會這樣使用
type fieldType = Partial<SUser>;
為了使代碼編譯,您可以執行以下操作:
type fieldType = { [K in keyof SUser]: string | number };
但是我不確定您將如何使用它,因為它將擴展為:
type fieldType = {
ID: string | number;
NAME: string | number;
MAIL: string | number;
PASSWORD: string | number;
GENDER: string | number;
BIRTHDATE: string | number;
ID_FB: string | number;
CREDIT: string | number;
ID_REFERRAL: string | number;
}
那不會給你你想要的錯誤。
您可能可能希望使用Partial <SUser>來創建具有所有屬性可選的類型
type fieldType = {
ID?: number;
NAME?: string;
MAIL?: string;
PASSWORD?: string;
GENDER?: number;
BIRTHDATE: string;
ID_FB?: string;
CREDIT?: number;
ID_REFERRAL?: number;
}
我假設這是因為在某些情況下您想傳入屬性的子集,但在其他情況下,則需要完整的字段。 請參見TypeScript部分接口對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.