[英]How can I type a typescript interface property using a predefined object?
export const OrderAuthorizationStates = {
unauthorized: "unauthorized",
waitingForAuthorization: "waitingForAuthorization",
authorized: "authorized"
}
export interface Customer {
id: number;
name: string;
orderAuthorizationStatus: "unauthorized" | "waitingForAuthorization" | "authorized"
}
這有效並給了我我想要的錯誤:
let customer: Customer;
if (customer.orderAuthorizationStatus === 'asdf') {
somecode
}
錯誤:“此條件將始終返回‘false’,因為類型‘‘unauthorized’ |‘waitingForAuthorization’ |‘authorized’’和‘‘asdf’’沒有重疊”
我也可以這樣使用它:
let customer: Customer;
if (customer.orderAuthorizationStatus === OrderAuthorizationStates.authorized) {
somecode
}
我無法解決的是,如何使用我的 OrderAuthorizationStates object 的對象屬性來鍵入我的客戶界面的接口屬性:
export interface Customer {
id: number;
name: string;
orderAuthorizationStatus: OrderAuthorizationStates.unauthorized | OrderAuthorizationStates.waitingforAuthorization | OrderAuthorizationStates.authorized
}
錯誤:找不到命名空間“OrderAuthorizationStates”
幫助將不勝感激!
字符串枚舉幾乎完全符合您的要求:
enum OrderAuthorizationStates {
Unauthorized = "Unauthorized",
WaitingForAuthorization = "WaitingForAuthorization",
Authorized = "Authorized"
}
interface Customer {
id: number;
name: string;
orderAuthorizationStatus: OrderAuthorizationStates;
}
let customer: Customer = { id: 1, name: "RichN", orderAuthorizationStatus: OrderAuthorizationStates.Unauthorized};
if (customer.orderAuthorizationStatus === "Unauthorized") {
console.log("Customer is unauthorized");
}
// Authorize it!
customer.orderAuthorizationStatus = OrderAuthorizationStates.Authorized;
if (customer.orderAuthorizationStatus === OrderAuthorizationStates.Authorized) {
console.log("Customer is now authorized");
}
// Output:
// Customer is unauthorized
// Customer is now authorized
此外,如果你這樣做if (customer.orderAuthorizationStatus === 'asdf')
你會得到錯誤'This condition will always return 'false' since the types 'OrderAuthorizationStates' and '"asdf"' have no overlap.',其中是你想要的。
找到了一種不使用枚舉的方法。
創建一個從 object 推斷出的類型:
export const OrderAuthorizationStatuses = {
unauthorized: 'unauthorized',
waitingForAuthorization: 'waitingForAuthorization',
authorized: 'authorized'
}
type OrderAuthorizationStatus = typeof OrderAuthorizationStatuses[keyof typeof OrderAuthorizationStatuses]
現在,您可以在整個應用程序中使用 object 鍵作為變量,而不會對 enum.member 有任何類型誤解,您可以在其上使用所有 object 方法,此外,您還可以使用它來鍵入接口屬性或任何其他內容:
export interface Customer {
id: number;
name: string;
orderAuthorizationStatus: OrderAuthorizationStatus
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.