Cyberduck
Cyberduck

Reputation: 881

make typescript to allow destructuring of undefined

I was migrating my code from JS to TS.

Now, My component takes array of objects, each dependent on the key

interface a {
 name?: string 
 lastName?: string 
}

interface b {
 email?: string 
 phone?: number 
}


const options:a | b = {email: '[email protected]'}

const {
 email, 
 phone, 
 name, 
 lastName 
} = options
 
 

Typescript here throws an error saying (say on email) something like this

Property 'name' does not exist on type 'b'
Property 'lastName' does not exist on type 'b'

Any idea how I can fix such errors? I have handled the undefined thing later in my code (this isn't actual code, just an example code).

Upvotes: 1

Views: 320

Answers (2)

bergerg
bergerg

Reputation: 995

You are using a type union here which means that options will have defined only the properties that are common for both a and b.

So for example if:

interface a {
    name: string;
    lastName: string;
}

interface b {
    name: string;
    age: number;
}

const options: a | b;

Then options will have only name property defined.

In your case there is nothing in common between a and b so options is practically an "empty" interface;

What you need here is type intersection.

If you define it as

const options: a & b = {}

then options will have all of the properties from both interfaces.

Upvotes: 1

C-lio Garcia
C-lio Garcia

Reputation: 710

According this, my solution could be:

interface a {
        name?: string 
        lastName?: string 
    }
       
       interface b {
            email?: string 
            phone?: number 
       }

       const something:a | b = {
           name: "Célio",
           lastName: "Garcia",
           email: "[email protected]",
           phone: 92100000
       }

       const options:a & b = {...something}

const {
 email, 
 phone, 
 name, 
 lastName 
} = options;

Hope it help someone who facing the issue.

Upvotes: 0

Related Questions