声明字符串枚举并使用它们的更好方法是Typescript


enum ROUTES {
REQUEST_OTP = 'REQUEST_OTP',
LOGIN = 'LOGIN',
}
export const urls: { [key: string]: string } = {
[ROUTES.REQUEST_OTP]: '/v1/auth/otp',
[ROUTES.LOGIN]: '/v1/auth/login',
};
export function getUrl(route: string) {
return BASE_URL + urls[route];
}

有没有更好的方法来写ROUTES枚举,而不是在它旁边重复写字符串文字?

在我编写字符串枚举的代码中似乎有代码重复。

尝试映射类型:

type ROUTE_KEY = 'REQUEST_OTP' | 'LOGIN';
export const urls: { [key: string]: string } = {
REQUEST_OTP: '/v1/auth/request-otp',
LOGIN: '/v1/auth/login/?version=v2',
};
export function getUrl(route: ROUTE_KEY) {
return BASE_URL + urls[route];
}

在这种情况下避免冗余的关键是在利用类型推理的同时根据值计算类型。每个JavaScript表达式都有一个相应的TypeSript类型。正如Bergi所说,我们可以通过在类型位置使用typeof运算符从值中获得类型。与keyof类型运算符一起,我们使用它来计算urls中所有属性键的并集类型。

export const urls = {
EQUEST_OTP: '/v1/auth/request-otp',
LOGIN: '/v1/auth/login/?version=v2'
};
export type RouteKey = keyof typeof urls;
export function getUrl(route: RouteKey) {
return BASE_URL + urls[route];
}

游乐场链接

在上面,我们使用typeof类型运算符来获得值urls的类型,即

{
REQUEST_OTP: string,
LOGIN: string
}

然后,我们使用keyof类型运算符来计算由该类型的属性键组成的并集类型,即

'REQUEST_OTP' | 'LOGIN'

请注意变量urls没有类型注释。类型推理的使用不仅增加了简洁性,而且产生了比{ [key: string]: string }强得多的类型。

或者,我们实际上可以不声明类型别名RouteKey,只写

export function getUrl(route: keyof typeof urls) {
return BASE_URL + urls[route];
}

目前尚不清楚这是否更好,因为您不清楚当前样本的缺点。然而,我会这样写:


type RouteKey = 'request-otp' | 'login';

export const urls: { [key: RouteKey]: string } = {
'request-otp': '/v1/auth/otp',
'login:': '/v1/auth/login',
};

export function getUrl(route: RouteKey) {
return BASE_URL + urls[route];
}

最新更新