typescript 如何在Typescript中获取变量类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35546421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a variable type in Typescript?
提问by Hongbo Miao
I have a variable.
我有一个变量。
abc:number|string;
How can I check its type? I want to do something like below:
我如何检查它的类型?我想做如下事情:
if (abc.type === "number") {
// do something
}
回答by basarat
For :
为了 :
abc:number|string;
Use the JavaScriptoperator typeof
:
使用JavaScript运算符typeof
:
if (typeof abc === "number") {
// do something
}
TypeScript understands typeof
打字稿理解 typeof
This is called a typeguard.
这称为打字员。
More
更多的
For classes you would use instanceof
e.g.
对于您将使用的课程,instanceof
例如
class Foo {}
class Bar {}
// Later
if (fooOrBar instanceof Foo){
// TypeScript now knows that `fooOrBar` is `Foo`
}
There are also other type guards e.g. in
etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html
还有其他类型保护,例如in
等 https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html
回答by Laurens
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof
我想补充一点,TypeGuards 只适用于字符串或数字,如果你想比较一个对象使用 instanceof
if(task.id instanceof UUID) {
//foo
}
回答by Kokkonda Abhilash
I have checked a variable if it is a boolean or not as below
我已经检查了一个变量是否是布尔值,如下所示
console.log(isBoolean(this.myVariable));
Similarly we have
同样我们有
isNumber(this.myVariable);
isString(this.myvariable);
and so on.
等等。
回答by artgrohe
The other answers are right, but when you're dealing with interfacesyou cannot use typeof or instanceof because interfaces don't get compiled to javascript.
其他答案是正确的,但是当您处理接口时,您不能使用 typeof 或 instanceof,因为接口不会被编译为 javascript。
Instead you can use a typecast + function checktypeguard to check your variable:
相反,您可以使用typecast + function checktypeguard 来检查您的变量:
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();
}
}
And this is the compiled JavaScript in ES2017:
这是在 ES2017 中编译的 JavaScript:
function start(vehicle) {
vehicle.drive();
if (vehicle.ringTheBell) {
const bike = vehicle;
bike.ringTheBell();
}
else {
const car = vehicle;
car.honkTheHorn();
}
}