如何使用'const'值作为类型?

时间:2020-04-08 04:38:16

标签: typescript

const X = "x";
let a:"x"; // This is allowed
let b:X;   // This is not allowed

有什么办法可以说服打字稿允许我使用上面的第3行?我将在很多地方使用该字符串进行检查等,并且最好将常量值用作类型。

1 个答案:

答案 0 :(得分:3)

在声明X之后,然后使用typeof提取其类型,并在其他地方使用该类型:

const x = "x";
type xType = typeof x;

let b: xType;
// OK:
b = 'x';
// Error:
b = 'y'

由于xconst,因此推断类型为分配给它的文字'x'。 (如果您使用let,则需要使用let x: 'x' = 'x';let x = 'x' as const键入注释)