A service is calling our API. It can call us with these types of JSON bodies:
const missingProperty = {}
const value = { foo: "bar" }
It will never call us with these bodies:
const nullish = { foo: null }
const undefinedish = { foo: undefined }
Is there a way to define a type that works this way? Here’s what I’ve tried, but it allows all possibilities:
type Foo = {
foo?: string,
}
type Foo2 = {
foo: string | undefined,
}
This doesn’t allow an empty object:
type Foo = {
foo: string | never,
}
const missing: Foo = {} // Unwanted error
const value: Foo = { foo: "bar" }
const nullish: Foo = { foo: null } // Wanted error
const undefinedish: Foo = { foo: undefined } // Wanted error
>Solution :
You’re looking for the exactOptionalPropertyTypes option.
If true :
interface MyObject {
myProperty?: string; // Optional, and when present, it must be a string.
}
const obj1: MyObject = {}; // Valid: myProperty is absent
const obj2: MyObject = { myProperty: "Hello" }; // Valid: myProperty is a string
const obj3: MyObject = { myProperty: undefined }; // Invalid: undefined is not assignable
const obj4: MyObject = { myProperty: null }; // Invalid: null is not assignable