乐闻世界logo
搜索文章和话题

How to get a variable type in Typescript?

1 个月前提问
1 个月前修改
浏览次数21

1个答案

1

在TypeScript中,获取变量的类型可以通过多种方式实现。以下是一些常用的方法:

1. 使用 typeof 操作符

typeof 操作符可以用来获取一个变量的基本类型,例如 string, number, boolean 等。这是JavaScript中也支持的操作,但在TypeScript中,它还可以在类型守卫和类型推断中发挥作用。

例子:

typescript
let age: number = 30; let ageType: string = typeof age; // 'number' if (typeof age === 'number') { console.log('Age is a number.'); }

2. 使用 instanceof 操作符

当你需要确认一个对象是否是某个类的实例时,可以使用 instanceof 操作符。这在处理类和继承时非常有用。

例子:

typescript
class Person { name: string; constructor(name: string) { this.name = name; } } let person = new Person("Alice"); if (person instanceof Person) { console.log('person is an instance of Person'); }

3. 自定义类型保护函数

TypeScript 允许定义自己的类型保护逻辑,通过定义一个返回值是类型谓词的函数。

例子:

typescript
function isNumber(x: any): x is number { return typeof x === "number"; } function process(input: number | string) { if (isNumber(input)) { console.log('Input is a number'); } else { console.log('Input is a string'); } } process(10); // Output: Input is a number process("Hello"); // Output: Input is a string

4. 使用 TypeScript 类型查询

TypeScript 提供了一种获取变量类型的语法,使用 typeof 关键字在类型上下文中获取另一个变量的类型。

例子:

typescript
let initial = "test"; type StringType = typeof initial; // 'string' let num: StringType; num = "Hello"; // 正确 num = 123; // 错误,Type 'number' is not assignable to type 'string'

这些方法可以根据您的具体需求和上下文选择使用。在实际开发中,正确地识别和使用类型不仅可以帮助我们更好地利用TypeScript的强类型系统,还能提高代码的可维护性和可读性。

2024年8月2日 14:06 回复

你的答案