如何执行此操作? :
type Brain = ...;
type Body = ...;
f = (part: Brain| Body) => {
// An error occurs here:
// Brain' only refers to a type, but is being used as a value here.
if (typeof part === Brain) {
// do something...
}
}
如果需要更多信息,请告诉我。
答案 0 :(得分:3)
类型别名和接口仅在编译时存在,因此您不能真正基于它们进行任何运行时检查。
根据需要,可以使用以下几种方法之一:
in
运算符作为类型保护。最简单的方法是使用in
运算符检查仅存在以下一种类型的属性的存在:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
const f = (part: Brain | Body) => {
if ('brainSize' in part) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
如果要更加确定,可以使用自定义类型防护来手动检查接口的所有属性:
type Brain = { brainSize: number, eyeColor: string };
type Body = { weight: number };
function isBrain(part: unknown): part is Brain {
let maybeBrain = part as Brain
return maybeBrain
&& typeof maybeBrain.brainSize === "number"
&& typeof maybeBrain.eyeColor === "string"
}
const f = (part: Brain | Body) => {
if (isBrain(part)) {
part.brainSize //ok
part.eyeColor // also ok
} else {
part.weight //ok
}
}
最严格的选择是使用typescript-is
来生成类似于out type guard的代码,但这意味着用我个人不推荐的ttypescript
替换默认编译器。