【问题标题】:Excluding specific strings from type从类型中排除特定字符串
【发布时间】: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

【问题讨论】:

标签: typescript


【解决方案1】:

正如@Alex 所说,当前的 TS 似乎不可能。但是,您可以对函数参数做类似的事情:

type TestName = 'test1' | 'test2' | 'test3';

type NotTestName<T> = T extends TestName ? never : T;
function myFunc<T>(myValue: NotTestName<T>) {}

现在,调用此函数的关键部分是确保缩小值,因为 string 实际上不属于 TestName 类型,因此它将通过测试:

// Allowed
myFunc('test' as const);
myFunc('abc' as const);

// Not allowed
myFunc('test1' as const);
myFunc('test2' as const);
myFunc('test3' as const);

最后,如果您需要像您的帖子中那样的最终 const 值,您可以将其用作辅助函数:

type TestName = 'test1' | 'test2' | 'test3';

type NotTestName<T> = T extends TestName ? never : T;
function h<T>(value: NotTestName<T>): T { return value; }

// Allowed
const name = h('test' as const);

// Not allowed
const name = h('test1' as const);
const name = h('test2' as const);
const name = h('test3' as const);

You can run it in this playground

请记住,如果字符串没有变窄,您将错误地通过测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多