export interface TEST {
action: 'action1' | 'action2' | 'action3',
params: User | BadUser
}
interface User {
name: string | null,
date: string | null,
...
}
interface BadUser {
badName: string | null,
badDate: string | null,
...
}
How to acces someUser.params.name or someBadUser.params.badName correctly ?
CodePudding user response:
You may use the in
operator to check if a field is present on the params
:
function something(thing: TEST) {
if ("name" in thing.params) {
return thing.params.date;
} else {
return thing.params.badDate;
}
}
CodePudding user response:
let test: TEST = {};
return test.params.name ?? test.params.badName;
or
return test.params.date ?? test.params.badDate;