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?
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).
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.
TypeScript has two special types, Null and Undefined, that have the values null and undefined respectively.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With