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?
This question is related to
typescript
nullable
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).
see if this flowchart helps - https://github.com/bcherny/language-types-comparison#typescript
Just add a question mark ?
to the optional field.
interface Employee{
id: number;
name: string;
salary?: number;
}
You can just implement a user-defined type like the following:
type Nullable<T> = T | undefined | null;
var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok
var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok
// Type 'number[]' is not assignable to type 'string[]'.
// Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,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
.
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
type MyProps = {
workoutType: string | null;
};
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).
function broken(name: string | null): string {
function postfix(epithet: string) {
return name.charAt(0) + '. the ' + epithet; // error, 'name' is possibly null
}
name = name || "Bob";
return postfix("great");
}
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet; // ok
}
name = name || "Bob";
return postfix("great");
}
Reference. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
Source: Stackoverflow.com