如何声明对象数组或对象?

时间:2019-11-05 17:56:02

标签: typescript

我正在进行API调用,该调用在成功时返回对象数组,在失败时返回错误对象。

我在两个接口之间使用type和or运算符进行了类似的尝试:

interface Foo {
  something: string;
}

interface Bar {
  somethingElse: string;
}

type SampleType = Foo[] | Bar;

const data: SampleType = [{ something: 'data ' }];

if (data.somethingElse) {
  // underlines somethingElse with error: Property 'somethingElse' does not exist on type 'Foo[]'.ts(2339)
}

但是linter强调了其他内容,错误为Property 'somethingElse' does not exist on type 'Foo[]'. ts(2339)

我应该如何正确输入?

1 个答案:

答案 0 :(得分:0)

您应该编写User-Defined Type Guard来检查data是否为Bar类型。

function isBar(val: unknown): val is Bar {
    return (val as Bar).somethingElse !== undefined;
}

完整示例:

interface Foo {
  something: string;
}

interface Bar {
  somethingElse: string;
}

function isBar(val: unknown): val is Bar {
    return (val as Bar).somethingElse !== undefined;
}

type SampleType = Foo[] | Bar;

const data: SampleType = [{ something: 'data ' }];

if (isBar(data) && data.somethingElse) {
  throw new Error("Invalid data!")
}

if (data) {
  // data is of type Foo[] now
}