To begin with, you must narrow down the type before assigning unique attributes that are not shared.
There are two options available depending on your specific situation:
- Incorporate a common attribute and assign distinct values to differentiate between them.
// First approach
interface Foo {
id: string;
name: string;
type: "foo";
}
interface Bar {
id: string;
phoneNumber: number;
type: "bar";
}
function baz(input: Foo | Bar) {
if (input.type === "bar") {
input.phoneNumber
}
if (input.type === "foo") {
input.name
}
}
- Determine if the key exists within the object.
// Second approach
interface Foo2 {
id: string;
name: string;
}
interface Bar2 {
id: string;
phoneNumber: number;
}
function baz2(input: Foo2 | Bar2) {
if ('phoneNumber' in input) {
input.phoneNumber // The type will be Bar2.
}
if ('name' in input) {
input.name // The type will be Foo2.
}
}
Playground