注意: 如果您是 TypeScript 新手,请先查看我们的 TypeScript 入门 教程。
在 TypeScript 中,typeof
运算符可以用于两种方式
- 运行时,它返回值的类型,如字符串(
string
、number
等)。 - 编译时,它允许你重用现有变量的类型。
让我们看一个例子,
let word: string = "hello";
// Compile-time use (type copying)
let typeOfWord: typeof word; // typeOfWord is of type 'string'
// Runtime use (type checking)
console.log(typeof word);
输出
string
在这里,typeof word
将 word
变量的 string
类型复制过来,并赋给 typeOfWord
。
typeof 类型
运行时,typeof
运算符返回以下字符串值之一:
类型 | typeof 结果 |
---|---|
字符串 |
"string" |
Number |
"number" |
BigInt |
"bigint" |
布尔型 |
"boolean" |
对象 |
"object" |
Symbol |
"symbol" |
undefined |
"undefined" |
null |
"object" |
function | "function" |
typeof 示例
示例 1:字符串的 typeof
const str: string = 'Hello';
console.log(typeof str); // string
示例 2:数字的 typeof
const num: number = 42;
console.log(typeof num); // number
示例 3:布尔值的 typeof
const flag: boolean = true;
console.log(typeof flag); // boolean
示例 4:对象的 typeof
const obj: { name: string } = { name: 'Sam' };
console.log(typeof obj); // object
示例 5:函数的 typeof
function greet(): void {}
console.log(typeof greet); // function
typeof 运算符的用法
1. 调试
你可以使用 typeof
来检查变量的类型,这有助于调试或在运行时验证类型。
let message: string = "Hello, World!";
console.log(typeof message); // string
2. 在类型定义中
你可以在编译时使用 typeof
来引用类型定义中变量的类型。
const user = { name: "John", age: 30 };
type UserType = typeof user;
let anotherUser: UserType = { name: "Alice", age: 25 };
3. 在条件语句中
你可以在条件语句中使用 typeof
,根据变量的类型执行不同的操作。
let value: string | number = "Hello";
if (typeof value === "string") {
console.log("The value is a string"); // The value is a string
}
else if (typeof value === "number") {
console.log("The value is a number");
}
更多关于 TypeScript typeof 运算符
运行时和编译时使用
与 JavaScript 一样,typeof
可以在运行时用来检查值的类型。
但 TypeScript 还增加了一项强大功能——你可以在编译时使用 typeof
来引用变量的类型。
const age = 25;
console.log(typeof age); // number
type AgeType = typeof age;
// AgeType is now inferred as: number
在这里,TypeScript 展示了 typeof 如何在运行时检查类型,以及如何在编译时提取变量的类型。