是否可以为除特定字符串文字之外的任何字符串创建类型?
type FooString = 'foo' | string
type Foo = 'foo'
type NotFoo = ?
目标:
const a: NotFoo = 'foo'; // error
const b: NotFoo = 'bar'; // ok
条件类型会起作用:
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 不是您可以作为参数提供的东西。
| 归档时间: |
|
| 查看次数: |
1109 次 |
| 最近记录: |