Data types in Typescript
Primitive types
1. boolean: true/false
2. number: whole numbers and floating point values
3. string: text values like "TypeScript"
4. bigint: whole numbers and floating point values, but allows larger negative and positive numbers than the number
type
5. symbol: are used to create a globally unique identifier
6. null and undefined: are the same as null and undefined of Javascript respectively
Special types
1. any:
- is a type that disables type checking and effectively allows all types to be used
let anyValue: any
anyValue = 'Typescript';
anyValue = 1;
const length = unknownValue.length;
// No compilation error. (But you can get runtime error)
2. unknown:
- is a similar, but safer alternative to
any
.TypeScript will preventunknown
types from being used
let unknownValue: unknown;
unknownValue = 'Typescript';
unknownValue = 1;
const length = unknownValue.length;
// Typescript will throw error "TS18046: 'unknownValue' is of type 'unknown'."
// You need to use type-checking before we can do that with unknown type
if (typeof unknownValue === 'string'){
const length = unknownValue.length;
}
3. never:
4. void
- is used where there is no data. For example, if a function does not return any value
- you can only assign undefined to void (also null of you do not turn on strictNullChecks)
const doSomethingAndDoNotReturnValue = (): void => {
console.log('A function do something but do not return any value');
};