【问题标题】:Can you make a smaller, more restricted type from an existing type?你能从现有类型中制作出更小、更受限制的类型吗?
【发布时间】:2019-11-23 23:17:07
【问题描述】:

假设我有这个类型声明:

type Foo = 'a' | 'b' | 'c';
type Bar = 'a' | 'b' ;

是否可以将 Bar 表示为 Foo 的子集?

我知道总是可以将Foo 表达为Bar 的超集,但在我的情况下,反过来会感觉更符合域。

【问题讨论】:

标签: typescript types


【解决方案1】:

您只需使用Exclude pre-defined conditional type

type Foo = 'a' | 'b' | 'c';
type Bar = Exclude<Foo, 'c'>;

const Bar = 'a';

请注意,以下内容可以正常工作,即使乍一看可能感觉不对:

type Bar = Exclude<Foo, 'd'>

playground


您还可以将其与index types 结合使用以达到有趣的目的:

type Foo = 'a' | 'b' | 'c';
type AnObject = { c: boolean }
type Bar = Exclude<Foo, keyof AnObject>

const myVar: Bar = "a";

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2017-05-19
      • 2023-02-02
      • 2014-03-10
      • 2015-05-31
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      相关资源
      最近更新 更多