简体   繁体   中英

fallback for the entire typescript interface?

I know we can set optional property using ? in interface but how to make the entire interface fallback to null or emtpy object?

interface MyType {
   abc: string
   def?: number
}

I tried

interface MyType {
   abc: string
   def?: number
} | {}

but now luck.

I'd find the easiest way is to not pollute the type more than necessary and have a fallback as eg:

var MyObject: MyType | {} | undefined;

// Then it can take
MyObject = {};
MyObject = undefined;
MyObject = {abc:"abc"}
MyObject = {abc:"abc", def:1}

You can use the Partial type

https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt

interface MyType {
 abc: string
 def?: number
}

const obj: Partial<MyType> = {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM