如何检查 TypeScript 中的自定义类型

举报
Q神 发表于 2023/06/23 10:53:27 2023/06/23
【摘要】 在 JavaScript 中,您可以使用typeof关键字来检查值的类型:const fruit = 'apple';console.log(typeof fruit);// Output: 'string'const year = 2022;console.log(typeof year);// Output: 'number'const isOpen = true;console.log...

在 JavaScript 中,您可以使用typeof关键字来检查值的类型:

const fruit = 'apple';
console.log(typeof fruit);
// Output: 'string'

const year = 2022;
console.log(typeof year);
// Output: 'number'

const isOpen = true;
console.log(typeof isOpen);
// Output: 'boolean'

const person = {
  name: 'Thomas Anderson',
  age: 32,
};
console.log(typeof person);
// Output: 'object'

因此,如果你想检查一个值是否是某种类型,你可以使用关键字typeof

const fruit = 'apple';

if (typeof fruit === 'string') {
  console.log(`${fruit} is a string`);
}

const year = 2022;

if (typeof year === 'number') {
  console.log(`${year} is a number`);
}

但是,如果您想检查 TypeScript 中的值是否为某种类型,则typeof关键字的工作方式与上面的 JavaScript 示例中的工作方式不同。

type Fruit = 'apple' | 'orange' | 'banana';

const myFruit = 'apple';

// This will NOT work ❌
if (typeof myFruit === 'Fruit') {
  console.log(`${myFruit} is a fruit`);
}

您无法在运行时使用typeof关键字来检查 TypeScript 类型,因为 TypeScript 在编译期间会删除类型注释、接口、类型别名和其他类型系统构造。

那么,如何检查 是否myFruit是 的类型Fruit

步骤 1 — 类型推断

将类型定义Fruit为文字值数组,TypeScript 将从这些值推断类型:

const fruit = ['apple', 'orange', 'banana'] as const;
type Fruit = (typeof fruit)[number];

第 2 步 — 类型保护

使用用户定义的类型保护来检查您的自定义类型:

const fruit = ['apple', 'orange', 'banana'] as const;
type Fruit = (typeof fruit)[number];

const isFruit = (x: any): x is Fruit => fruit.includes(x);

isFruit()函数将检查其参数是否在fruit数组中,如果是,则将其参数缩小为Fruit

const fruit = ['apple', 'orange', 'banana'] as const;
type Fruit = (typeof fruit)[number];

const isFruit = (x: any): x is Fruit => fruit.includes(x);

const myFruit = 'apple';

// This will work ✅
if (isFruit(myFruit)) {
    console.log(`${myFruit} is a type of Fruit`);
} else {
  console.log(`${myFruit} is NOT a type of Fruit`)
}
// Output: "apple is a typeof Fruit"


现在,当我们的值不属于水果数组的一部分时,我们还可以看到类型检查正在工作:

const fruit = ['apple', 'orange', 'banana'] as const;
type Fruit = (typeof fruit)[number];

const isFruit = (x: any): x is Fruit => fruit.includes(x);

const myFruit = 'mango';

// This will work ✅
if (isFruit(myFruit)) {
    console.log(`${myFruit} is a type of Fruit`);
} else {
  console.log(`${myFruit} is NOT a type of Fruit`)
}
// Output: "mango is NOT a typeof Fruit"
// (In reality mango is a fruit, but since it is not
// a part of our fruit array, it is NOT a type Fruit)


总之

TypeScript只存在于编译时,在运行时被完全丢弃。

这意味着您不能使用typeof关键字来检查自定义类型。

相反,您可以type inference与 a 一起使用type guard来检查自定义类型。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。