iFr*_*cht 8 string types literals unions typescript
我想将字符串缩小为字符串文字联合。换句话说,我想检查字符串是否是我的文字联合的可能值之一,以便这将起作用(如果运算符couldbe存在)。
type lit = "A" | "B" | "C";
let uni: lit;
let str = "B";
if(str couldbe lit){
uni = str;
} else {
doSomething(str);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我尝试使用if (str instanceof lit),但这似乎不起作用。使用keyof迭代字符串联合也不起作用,因为允许的值本身不是键。
一种方法是switch对每个可能的值使用一个 case,但如果lits 允许的值发生变化,这可能会导致细微的错误。
am0*_*0wa 17
如果您像我一样讨厌 switch case:
\nssince TypeScript 3.4 \xe2\x80\x93 const 断言,也可以从字符串数组生成联合类型 ^_^
const lits = <const>["A", "B", "C"];\ntype Lit = typeof list[number]; // "A" | "B" | "C"\n\nfunction isLit(str: string): str is Lit {\n return !!lits.find((lit) => str === lit);\n}\nRun Code Online (Sandbox Code Playgroud)\n
您可以使用用户定义的类型防护。
type lit = "A" | "B" | "C";
let uni: lit;
let str = "B";
function isLit(str: string): str is lit {
return str == "A" || str == "B" || str == "C";
}
function doSomething(str: string) {
}
if (isLit(str)) {
uni = str;
}
else {
doSomething(str);
}
Run Code Online (Sandbox Code Playgroud)
添加:
为了避免重复编辑,class可用于编译时和运行时。现在您所要做的就是只编辑一处。
class Lit {
constructor(public A = 0, public B = 0, public C = 0) {}
}
type lit = keyof Lit;
let uni: lit;
function isLit(str: string): str is lit {
let lit = new Lit();
return (str in lit) ? true : false;
}
Run Code Online (Sandbox Code Playgroud)