[英]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.