How to declare a type as nullable in TypeScript?
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>;
}
Bonus:
To make Nullable
behave like a built in Typescript type, define it in a global.d.ts
definition file in the root source folder. This path worked for me: /src/global.d.ts
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';
}