Since Typescript 2.1, you can do it the other way around with the keyof
operator.
The idea is as follows. Since string literal type information isn't available in runtime, you will define a plain object with keys as your strings literals, and then make a type of the keys of that object.
As follows:
// Values of this dictionary are irrelevant
const myStrings = {
A: "",
B: ""
}
type MyStrings = keyof typeof myStrings;
isMyStrings(x: string): x is MyStrings {
return myStrings.hasOwnProperty(x);
}
const a: string = "A";
if(isMyStrings(a)){
// ... Use a as if it were typed MyString from assignment within this block: the TypeScript compiler trusts our duck typing!
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…