How to declare a type as nullable in TypeScript?

How to declare a type as nullable in TypeScript?

I have an interface in TypeScript.
interface Employee{
id: number;
name: string;
salary: number;
}

I would like to make ‘salary’ as a nullable field (Like we can do in C#). Is this possible to do in TypeScript?

Solutions/Answers:

Solution 1:

All fields in JavaScript (and in TypeScript) can have the value null or undefined.

You can make the field optional which is different from nullable.

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

Solution 2:

Union type is in my mind best option in this case:

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

EDIT : For this to work as expected, you should enable the strictNullChecks in tsconfig.

Solution 3:

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

Solution 4:

To be more C# like, define the Nullable type like this:

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}

Solution 5:

type MyProps = {
  workoutType: string | null;
};

Solution 6:

i had this same question a while back.. all types in ts are nullable, because void is a subtype of all types (unlike, for example, scala).

Related:  How to pass json POST data to Web API method as an object?

see if this flowchart helps – https://github.com/bcherny/language-types-comparison#typescript