【发布时间】:2023-02-14 02:15:10
【问题描述】:
如果我的类型为:
type TestName = 'test1' | 'test2' | 'test3';
如何定义不包含上述内容的字符串类型?
type CustomName = `${string}` /// need to exclude TestName
const name: CustomName = 'test'; // allowed
const name: CustomName = 'test1'; // not allowed
const name: CustomName = 'test2'; // not allowed
const name: CustomName = 'test3'; // not allowed
【问题讨论】:
-
这是不可能的,因为 NOT 类型目前无法在 TypeScript 中表达。但是,您可以编写一个函数来推断和验证其参数:tsplay.dev/NnlKxW
-
作为参考,这被称为否定类型,目前是实验性的github.com/Microsoft/TypeScript/pull/29317
标签: typescript