Using parameter destructuring with null coalescing, typescript is having a issue with the optional name
attribute. I do not want to change the original code to const name = data?.resource?.name ?? []
which probably would make typescript happy. How can I change the typescript so it would handle the parameter destructuring with null coalescing?
code
private _getName(data: Data) {
const { name } = data.resource ?? [];
type:
type Data = {
fullUrl?: string,
resource?: {
active?: boolean,
address?: Address[],
birthDate?: string,
gender?: string,
id?: string,
identifier?: Indentifier[],
materialStatus?: Coding[],
meta?: Security[],
name?: Name[],
resourceType?: string,
telecom?: Telecom[],
},
search?: {
extension?: Extension[],
mode?: string,
score: number,
}
};
error:
error TS2339: Property 'name' does not exist on type '{ active?: boolean; address?: Address[]; birthDate?: string; gender?: string; id?: string; identifier?: Indentifier[]; materialStatus?: Coding[]; meta?: Security[]; name?: Name[]; resourceType?: string; telecom?: Telecom[]; } | undefined[]'.
73 const { name } = data.resource ?? []
2
Answers
This:
And this:
Are not logically equivalent.
The first one resolves to an array when
data.resource
isundefined
. Soconst name
is assigned a value of[]
.The second one expects whatever is on the right hand side of the
=
to have aname
property, and the value of thatname
property will be assigned toconst name
.But an array does not have a
name
property, so you get a type error, and at runtime would beundefined
.In order to make this work with destructuring you must make sure whatever is on the right side here has a
name
property.For example:
But that’s pretty silly.
I think that this:
Is the cleanest solution here. It’s not advisable to use destructuring assignment unless all possible values being destructured support the property being destructured.
See Typescript Playground. Click "Run" and see the console output for yourself.