typescript undefined on the entire interface

Viewed 825

How to declare the entire MyCustomObject interface can fallback to an empty object?

interface MyCustomObject {
   name: string, 
   age: number
}

Below case is safe, it has default property of name and age as fallback, but sometime if the obj is from other source like an api, it can be some other type like an empty {} or even an empty []

const obj: MyCustomObject = {
    name: "",
    age: 0
}

I tried this

interface MyCustomObject {
   name: string, 
   age: number
} | {}

it doesn't work that way.

2 Answers

the most correct way is to create a union

type IUnionType = MyCustomObject | {};

other ways to handle this is to make each property optional

interface MyCustomObject {
   name?: string, 
   age?: number
}

Or create an optional object property where a union is defined in the original interface.

interface MyCustomObject2 {
    obj: MyCustomObject | {}
}

examples

I have one interface having some member variables suppose my interface name is IUser and variable name is iUser. I have to make it undefine but I m getting error that we cannot make iUser = undefine so I did something like this.

    let obj: any;
    this.iUser = obj;
    obj = undefined

and it works for me

Related