4 min read
•Question 2 of 48easyWhat are the basic types in TypeScript?
Understanding primitive and basic types.
What You'll Learn
- Primitive types
- Array and tuple types
- Special types
Primitive Types
code.tsTypeScript
// String
let name: string = "John";
// Number
let age: number = 30;
// Boolean
let isActive: boolean = true;
// Null and Undefined
let n: null = null;
let u: undefined = undefined;Array Types
code.tsTypeScript
// Two ways to declare arrays
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b", "c"];Tuple
code.tsTypeScript
// Fixed length array with known types
let user: [string, number] = ["John", 30];Special Types
code.tsTypeScript
// any - opt out of type checking
let data: any = 4;
data = "string"; // OK
// unknown - safer than any
let value: unknown = 10;
if (typeof value === "number") {
console.log(value + 1); // OK after check
}
// void - no return value
function log(msg: string): void {
console.log(msg);
}
// never - never returns
function error(msg: string): never {
throw new Error(msg);
}