有没有办法从联合类型创建一个新类型,并删除一些选项?



让我们说我们有

type U = A | B | C

我们需要U型u,而没有一些选项

function f<T option U>(u: U): U without T {...}

我们如何表达

  1. 你有类型的联合
  2. t是u
  3. 的一种选择
  4. 返回的类型就像u,但没有某个选项

是的,使用stadard库中的排除。

type U = 'a' | 'b' | 'c';
type nonA = Exclude<U, 'a'>; // 'b' | 'c'

和您的功能

function f<T extends U>(u: U): Exclude<U,T> {...}

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types

100%工作示例

function withoutType<U, T extends U>(u: U) {
  return u as Exclude<U, T>;
}
type Union = string | number | Function;
let x = 5;
let y = withoutType<Union, Function>(x); // let x: string | number;

最新更新