我有一个变量.
abc:number|string;
Run Code Online (Sandbox Code Playgroud)
我该如何检查其类型?我想做类似下面的事情:
if (abc.type === "number") {
// do something
}
Run Code Online (Sandbox Code Playgroud)
bas*_*rat 109
用于:
abc:number|string;
Run Code Online (Sandbox Code Playgroud)
使用JavaScript运算符typeof:
if (typeof abc === "number") {
// do something
}
Run Code Online (Sandbox Code Playgroud)
TypeScript理解 typeof
这被称为打字机.
对于您将使用的课程,instanceof例如
class Foo {}
class Bar {}
// Later
if (fooOrBar instanceof Foo){
// TypeScript now knows that `fooOrBar` is `Foo`
}
Run Code Online (Sandbox Code Playgroud)
还有其他类型的警卫,例如in等 https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html
Lau*_*ens 38
我想补充一点,如果要比较对象使用instanceof,TypeGuard只能处理字符串或数字
if(task.id instanceof UUID) {
//foo
}
Run Code Online (Sandbox Code Playgroud)
art*_*ohe 24
其他答案是正确的,但是当您处理接口时,您不能使用 typeof 或 instanceof,因为接口不会被编译为 javascript。
相反,您可以使用typecast + function check typeguard 来检查您的变量:
interface Car {
drive(): void;
honkTheHorn(): void;
}
interface Bike {
drive(): void;
ringTheBell(): void;
}
function start(vehicle: Bike | Car ) {
vehicle.drive();
// typecast and check if the function exists
if ((<Bike>vehicle).ringTheBell) {
const bike = (<Bike>vehicle);
bike.ringTheBell();
} else {
const car = (<Car>vehicle);
car.honkTheHorn();
}
}
Run Code Online (Sandbox Code Playgroud)
这是在 ES2017 中编译的 JavaScript:
function start(vehicle) {
vehicle.drive();
if (vehicle.ringTheBell) {
const bike = vehicle;
bike.ringTheBell();
}
else {
const car = vehicle;
car.honkTheHorn();
}
}
Run Code Online (Sandbox Code Playgroud)
Max*_*man 15
我怀疑您可以稍微调整一下您的方法并使用与此处示例类似的内容:
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
Run Code Online (Sandbox Code Playgroud)
Wil*_*een 10
要确定条件语句后变量的类型,可以使用类型保护。Typescript 中的类型保护如下:
允许您缩小条件块内某项类型范围的表达式。
换句话说,它是条件块内的表达式,打字稿编译器有足够的信息来缩小类型范围。该类型在类型保护块内将更加具体,因为编译器已推断出有关该类型的更多信息。
declare let abc: number | string;
// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
// abc: string
console.log('abc is a string here')
} else {
// abc: number, only option because the previous type guard removed the option of string
console.log('abc is a number here')
}
Run Code Online (Sandbox Code Playgroud)
除了typeof运算符之外,还有内置的类型保护器,例如instanceof,in甚至是您自己的类型保护器。
我检查了一个变量是否为布尔值,如下所示
console.log(isBoolean(this.myVariable));
Run Code Online (Sandbox Code Playgroud)
同样,我们有
isNumber(this.myVariable);
isString(this.myvariable);
Run Code Online (Sandbox Code Playgroud)
等等。