[英]how to define type for a constant using typescript?
如何在types
引用常量? 例如,我具有下面的常量值(例如A和B),并且需要创建一个动作类型,以便稍后可以在switch case
使用动作类型。
const PATH = '@@test/';
export const A = `${PATH}A`;
export const B = `${PATH}B`;
export type Action =
// UI actions
{ type: typeof A, payload: { a: any } }
| { type: B, payload: { b: boolean }}
//用法
const id = (state= initialState, action: Action) => {
const nextState = state;
switch (action.type) {
case A: {
const{a} = action.payload;
break;
}
case B: {
const { b} = action.payload;
break;
}
default:
break;
}
当前的TypeScript(从v2.5开始)缺乏连接字符串文字类型的能力。 当您在TypeScript中连接两个字符串文字时,仅知道结果类型为string
。 例如,它不知道以下是正确的:
const x = "x";
const xx: "xx" = x + x; // error!
在您的情况下,TypeScript推断A
和B
为string
值:
export const A = `${PATH}A`; // inferred as string
export const B = `${PATH}B`; // inferred as string
因此,由于在两种情况下type
属性都是相同的,所以Action
不被视为有区别的联合 :
export type Action =
{ type: typeof A, payload: { a: any } } |
{ type: typeof B, payload: { b: boolean } }
解决此问题的唯一方法是,您可以手动指定A
和B
的文字类型,并可能需要进行运行时检查以确保未错误配置常量。 是的,这很不幸 ,但是它可以工作:
const PATH = '@@test/';
export const A = "@@test/A";
export const B = "@@test/B";
if (!A.startsWith(PATH) || !B.startsWith(PATH)) {
throw new Error("Bad configuration");
}
现在, Action
是一个适当的可区分联合,当您switch
type
属性时,TypeScript会自动为您缩小类型:
declare const action: Action;
switch (action.type) {
case A: {
const { a } = action.payload; // okay
break;
}
case B: {
const { b } = action.payload; // okay
break;
}
default:
const assertNever: never = action; // okay
break;
}
希望能有所帮助; 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.