除特定字符串文字之外的任何字符串的 TypeScript 类型

Bis*_*hok 5 typescript

是否可以为除特定字符串文字之外的任何字符串创建类型?

type FooString = 'foo' | string

type Foo = 'foo'

type NotFoo = ?

目标:

const a: NotFoo = 'foo'; // error

const b: NotFoo = 'bar'; // ok

cap*_*ian 5

条件类型会起作用:

type FooString = 'foo' | string

type Foo = 'foo'
type NotFoo<T extends string> = T extends 'foo' ? never : T

const notFoo = <T extends string>(arg: NotFoo<T>):T => arg

const result = notFoo('hello') // ok
const result2 = notFoo('foo') // error

type Result = NotFoo<'foo'> // never
type Result2 = NotFoo<'bar'> // 'bar'
Run Code Online (Sandbox Code Playgroud)

游乐场链接

如果arg是foo,NotFooutil 将返回never类型。 nevertype 不是您可以作为参数提供的东西。