The primitive types
All primitive types are referenced in lowercase.
number,string,boolean,undefined,null...TS adds a couple of extra lowercase types solely related to its type-checking job:
any,unknown,void,never...Arrays can be declared either by
something[]orArray<something>;
Be careful: There also exists an uppercase
Numbertype, which is a different thing from lowercasenumber! Types likeNumber,String,Booleanrefer to the javascript functions that have those names.Be careful: Both types
{}andobjectrefer to an empty object. To declare an object that can receive any property, useRecord<string, any>.
Strict nulls
Unlike some other languages, types do not implicitly include
null;Ex: in Java, any variable can always also be null;
In TypeScript a type is declared as nullable through a type union:
type X = Something | null | undefinedA type can be narrowed as "not null" through control flow analysis. Ex:
const x = 2 as number | null
if (x) {
console.log(x) // x cannot be null inside this block
}You can tell the compiler to assume a variable is not null with the
!operator;
interface X {
optional?: { value: number }
}
const instance: X = {}
console.log(instance.optional.value) // TS will show error
console.log(instance.optional!.value) // assume "optional" existsLast updated
Was this helpful?