首页 > 解决方案 > TypeScript:键入以包含任何值,但预定义集中的值除外

问题描述

是否可以有一个类型包含任何值但预定义集中的值?

type Fruit = 'Apple' | 'Banana' | 'Orange'
type NotFruit = ???

const a: NotFruit = 'Carrot'; // Compiler OK.
const b: NotFruit = 'Apple';  // Compiler ERROR.

即是否存在NotFruit编译器根据我的代码中的注释响应的定义?

标签: javascripttypescript

解决方案


我会回答,Typescript 绝对不可能做到这一点。该语言中的集合没有否定运算符。

不过,您可以创建一个 instanceOf 类型保护。

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

type Fruit = "Apple" | "Orange";

function isFruit(fruit: string): fruit is Fruit {
    return !(['Apple', 'Orange'].includes(fruit));
}

推荐阅读