Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Amitabh Avatar asked Jun 20 '13 17:06

Amitabh


People also ask

How do I create a nullable variable in TypeScript?

Nullable type can invoke runtime error. So I think it's good to use a compiler option --strictNullChecks and declare number | null as type. also in case of nested function, although input type is null, compiler can not know what it could break, so I recommend use ! (exclamination mark).

Can string be null TS?

Just as in JavaScript, the null data type in TypeScript can have only one valid value: null . A null variable cannot contain other data types like number and string. Setting a variable to null will erase its content if it had any.

Is there null in TypeScript?

TypeScript has two special types, Null and Undefined, that have the values null and undefined respectively.


1 Answers

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'; } 
like image 145
Ryan Cavanaugh Avatar answered Oct 13 '22 02:10

Ryan Cavanaugh