How to access the difference member for merged interface in typescript?
Consider we have two interface A
and B
, how can开发者_开发问答 I get the difference member for merged interface?
interface A {
from: string,
items: number[],
}
interface B {
to: string,
items: number[],
}
type C = A | B;
function foo(fromOrTo: C) {
const result = fromOrTo.from || fromOrTo.to
// Get error: "from" or "to" don't exist in C
}
I know another way to implement this:
interface C {
from?: string,
to?: string,
items: number[],
}
function foo(fromOrTo: C) {
const result = fromOrTo.from || fromOrTo.to;
// This is a one of solutions.
}
You can use a type guard to check for the existence of the property you are interested in, and maintain type-safety downstream
interface A {
from: string,
items: number[],
}
interface B {
to: string,
items: number[],
}
type C = A | B;
function isFrom(fromOrTo: C): fromOrTo is A {
return (fromOrTo as A).from !== undefined
}
function isTo(fromOrTo: C): fromOrTo is B {
return (fromOrTo as B).to !== undefined
}
function someFn() {
if (isFrom(fromOrTo)) {
fromOrTo // Type 'A'
}
else {
fromOrTo // Type 'B'
}
}
function foo(fromOrTo: C) {
const result = isFrom(fromOrTo) ? fromOrTo.from : fromOrTo.to
}
TypeScript playground
精彩评论