Typescript
TypeScript extends JavaScript and enhances the developer experience.
Primitive Types
TypeScript has three primitive types that are frequently used: string, number, and boolean.
Type any
The any type is generic type used when a variable's type is unclear or hasn't yet been defined. The any type allows one to gradually opt-in and out of type checking during compilation, which is useful when converting existing JavaScript to TypeScript.
Type void
The void indicates a variable's lack of a type. It acts as the opposite type to any. It is especially useful in functions that don’t return a value.
Type unknown
The unknown type is the type-safe counterpart of any type. You can assign anything to the unknown, but the unknown isn’t assignable to anything but itself and any, without performing a type assertion of a control-flow-based narrowing. You cannot perform any operations on a variable of an unknown type without first asserting or narrowing it to a more specific type.
Difference between null and undefined:
In TypeScript, null and undefined are actual types, not just values and how strictly they're enforced depends on one compiler setting.
- With
strictNullChecksenabled (part ofstrict: true, and recommended),nullandundefinedare only assignable to themselves and toany. A variable typedstringcannot receivenullunless the type explicitly allows it via a union. - Without
strictNullChecks,nullandundefinedare treated as assignable to every type, which quietly defeats a lot of the safety TypeScript is meant to provide.
Type inference
TypeScript can often figure out a variable's type from its initial value, without you writing an annotation:
Annotations are still useful for function parameters (which can't be inferred from a value) and for widening a type on purpose.
Literal types
Beyond the general string/number/boolean types, TypeScript can narrow a type down to one exact value: