Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

Typescript property does not exist in a union

I have the following types:

Foo {
 foobar: any
}

Bar {
 fooBarBar: any;
}

A function defined as such:

this.api.submit(param: Foo | Bar)

usage:

this.api.submit(param.foobar) // does not exist on Bar

Error: Property 'foobar' does not exist on type 'Foo| Bar'.
  Property 'foobar' does not exist on type 'Bar '

My assumption was typescript would figure based on the union it could be either of these models, so why does it complain in this instance?

A workaround is to use the bracket notation param['foobar'] and the error will disappear...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What your definition says is that param will be either Foo or Bar, but there's no way for the compiler to decide which at the point you call param.foobar.

If you want to be able to discriminate, you can do something like this:

Foo {
    type: 'foo',
    foobar: any
}

Bar {
    type: 'bar',
    fooBarBar: any;
}
...
if (param.type === 'foo') {
    param.foobar; // the type guard in the if statement guarantees we've got an instance of Foo here
}

If what you wanted to say is that param will be both Foo and Bar, you need intersection types, i.e.: Foo & Bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...