发布于 2026-01-06 8 阅读
0

TypeScript - 使用技巧 - typeof typeof

TypeScript - 使用技巧 - typeof

类型

今天我想开始一个关于 TypeScript 的技巧和窍门系列。
我计划每周发布两到三篇。
在开始之前,我想解释一下我为什么会推出这个系列。
我推出这个系列的原因是,我每天都会在 TypeScript 文件中看到大量的`any`类型,所以我希望能够帮助开发者更好地学习 TypeScript 语言。

类型

今天我先从typeof运算符开始。typeof
运算符用于检测变量的类型。
简单介绍一下,typeof 也是 JavaScript 运算符,但在 TypeScript 中,它拥有更强大的功能。

JavaScript 中的 typeof 具有以下行为:

const valueString = "string";
const valueNumber = 1;
const valueBoolean = true;
const valueBigInt = 1n;
const valueFunction = () => true;
const valueUndefined = undefined;
const valueNull = null;
const object = {
  prop1: "value1",
  prop2: "value2",
};

console.log(typeof valueString); // string
console.log(typeof valueNumber); // number
console.log(typeof valueBoolean); // boolean
console.log(typeof valueBigInt); // bigint
console.log(typeof valueFunction); // function
console.log(typeof valueUndefined); // undefined
console.log(typeof valueNull); // object
console.log(typeof object); // object
Enter fullscreen mode Exit fullscreen mode

我们发现有些事情很奇怪:例如,当我们使用 typeof 获取空变量时,JavaScript 返回的是一个对象类型。

但在这里,我们看到了 TypeScript 中的相同示例:

type valueStringType = typeof valueString; // "string"
type valueNumberType = typeof valueNumber; // 1
type valueBooleanType = typeof valueBoolean; // true
type valueBigIntType = typeof valueBigInt; // 1n
type valueFunctionType = typeof valueFunction; // () => boolean
type valueUndefinedType = typeof valueUndefined; // undefined
type valueNullType = typeof valueNull; // null
type objectType = typeof object; // { prop1: string; prop2: string; }
Enter fullscreen mode Exit fullscreen mode

首先,对我们开发者来说,typeof 运算符的友好之处在于它能准确地转换类型,完全符合预期。这种优势在函数、null 和对象这三种类型上体现得尤为明显。

现在举一个更高级的例子:

const item = {
  id: '0000',
  name: 'Item',
  unit: {
    id: '1',
    code: 'PZ'
  },
  variants: [{
    id: '1',
    code: '001',
    color: 'FFFFFF'
  }]
};

type Item = typeof item;
type Unit = typeof item["unit"];
type Variant = typeof item.variants[number];
Enter fullscreen mode Exit fullscreen mode

在这个例子中,我们可以看到如何从复杂对象中提取简单类型。

我把该运营商的官方文档链接留给你。

今天就到这里了,
下次再见!

文章来源:https://dev.to/this-is-learning/typescript-tips-tricks-typeof-nfi