面试题-ts中的typeof

发布于:2025-06-23 ⋅ 阅读:(18) ⋅ 点赞:(0)

在 TypeScript 里,typeof操作符在类型系统和 JavaScript 运行时中的表现有所不同。下面详细介绍它对基本类型、对象、数组和函数的返回结果:

一、TypeScript 类型系统中的 typeof

在类型注解、泛型约束等类型相关的上下文中,typeof用于获取变量或表达式的类型

1. 基本类型
const num: number = 42;
const str: string = "hello";
const bool: boolean = true;
const nul: null = null;
const undef: undefined = undefined;
const sym: symbol = Symbol();

type NumType = typeof num;      // number
type StrType = typeof str;      // string
type BoolType = typeof bool;    // boolean
type NullType = typeof nul;     // null
type UndefType = typeof undef;  // undefined
type SymType = typeof sym;      // symbol

2. 对象

typescript

const person = {
  name: "Alice",
  age: 30,
};

type PersonType = typeof person;
// 等同于:
// {
//   name: string;
//   age: number;
// }
3. 数组
const numbers = [1, 2, 3];
const mixed = [1, "a", true];

type NumbersType = typeof numbers;      // number[]
type MixedType = typeof mixed;          // (number | string | boolean)[]
4. 函数
function add(a: number, b: number): number {
  return a + b;
}

type AddFnType = typeof add;
// 等同于:
// (a: number, b: number) => number

二、JavaScript 运行时中的 typeof

在表达式中,typeof返回一个表示值类型的字符串(这和 TypeScript 类型系统不同)。

1. 基本类型

typeof 42;           // "number"
typeof "hello";      // "string"
typeof true;         // "boolean"
typeof null;         // "object"(JavaScript 历史遗留问题)
typeof undefined;    // "undefined"
typeof Symbol();     // "symbol"
2. 对象
typeof { name: "Alice" };  // "object"
typeof [1, 2, 3];          // "object"
typeof null;              // "object"(注意:null 不是对象!)
3. 函数
typeof function() {};     // "function"
typeof Math.sqrt;         // "function"

三、TypeScript 中 typeof 的常见应用

1. 提取已有变量的类型
const config = {
  apiKey: "secret",
  timeout: 5000,
};

type ConfigType = typeof config;
// 等同于:
// {
//   apiKey: string;
//   timeout: number;
// }
2. 与 keyof 结合获取属性名联合类型
type ConfigKeys = keyof typeof config;  // "apiKey" | "timeout"
3. 泛型约束
function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

const timeout = getProperty(config, "timeout");  // number 类型

四、注意事项

  1. JavaScript 的 typeof null 问题

    javascript

    typeof null === "object";  // true(历史错误,无法修复)
    
  2. TypeScript 的 typeof 只能用于具体值

    type ErrorType = typeof number;  // 错误:不能直接对类型使用 typeof
    type CorrectType = typeof 42;    // 正确:对值使用 typeof
    
  3. 数组类型的特殊性

    const arr = [1, 2, 3];
    type ArrType = typeof arr;       // number[]
    type FirstElement = ArrType[0];  // number
    

总结

场景 TypeScript 类型系统 JavaScript 运行时
基本类型 获取具体类型(如 numberstring 返回字符串(如 "number"
对象 获取对象结构类型 返回 "object"
数组 获取元素类型的数组(如 number[] 返回 "object"
函数 获取函数签名类型 返回 "function"

合理运用 typeof 可以让你在 TypeScript 中更精准地进行类型定义和类型推导。


网站公告

今日签到

点亮在社区的每一天
去签到