Primitive data types
TypeScript supports several primitive data types that can be used to represent basic values in a program. These include:
- number: Used to represent numeric values, including integers and floating-point numbers.
- string: Used to represent text or string values.
- boolean: Used to represent true/false or boolean values.
- null: Used to represent the absence of any value.
- undefined: Used to represent a variable that has not been assigned a value.
- symbol: Used to represent a unique identifier for a value.
To use these data types in your TypeScript code, you can simply declare a variable and assign it a value of the desired type. For example:
let myNumber: number = 42;
let myString: string = "Hello, world!";
let myBoolean: boolean = true;
let myNull: null = null;
let myUndefined: undefined = undefined;
let mySymbol: symbol = Symbol();
Using the correct data types is important for several reasons. First, it helps to ensure that your code is type-safe and free of common errors, such as trying to perform arithmetic operations on non-numeric values. Second, it can help to improve the performance of your code by allowing the TypeScript compiler to optimize the generated JavaScript code.
In addition to these built-in data types, TypeScript also supports several advanced types, including arrays, tuples, and enums. These can be used to represent more complex data structures and values.
By understanding the different primitive data types in TypeScript and how to use them effectively in your code, you can write more robust and maintainable programs that are free of common errors and bugs.