Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In TypeScript, how do you define a property that can be absent but will never be null or undefined?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading