如何使用typescript定义常量的类型?
如何在如何使用typescript定义常量的类型?,typescript,typescript-typings,typescript2.0,Typescript,Typescript Typings,Typescript2.0,如何在类型中引用常量?例如,我有下面的常量值,如A和B,需要创建一个动作类型,以便稍后在开关案例中使用动作类型 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
类型中引用常量
?例如,我有下面的常量值,如A和B,需要创建一个动作类型,以便稍后在开关案例中使用动作类型
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
因此,由于类型
属性在两种情况下是相同的,因此操作
不被视为a:
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
是一个正确的区分联合,当您在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;
}
希望有帮助;祝你好运