繁体   English   中英

在打字稿中定义类型的方式,例如[接口的联合之一]和{// atrributes}

[英]Way to define a type in typescript like [one of union of interfaces] & {//atrributes}

// The way types defined:

interface SudoA {
    foo: string;
}

interface SudoB {
    bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
    super: boolean;
}

const baz: SuperSudo = {

} 
// typescript (3.1.6) says i have to define both `bar` and `foo` for the object

我期望的是放置super属性和其他属性(来自Sudo类型)应该是可选的。 问题; 这是一个错误的期望吗? 不管是还是否,这是如何实现的?

编辑
更正了baz的类型,我的错误是:/。
我期望对SuperSudo定义仅super属性就足够了,而来自接口联合的其他属性应该是可选的。

我可以定义一个新的类型
type SuperSudo<T> = T & {}但是最终使用SuperSudo<T> ,我觉得它很冗长。

EDIT2
更改标题

您是否考虑过使用类型鉴别器?

如果没有,则指定foobarfoobar都将始终满足联合类型。

用一个可能看起来像:

interface SudoA {
  _type: "a";
  foo: string;
}

interface SudoB {
  _type: "b";
  bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
  super: boolean;
}

const baz1_valid: SuperSudo = {
  _type: "a",
  super: true,
  foo: "bar",
}

const baz2_valid: SuperSudo = {
  _type: "b",
  super: true,
  bar: "foo",
}

字段名称不必是_type ,它必须是相同的字段名称,并且每个变量的类型值都不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM