𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗣𝗿𝗶𝗺𝗶𝘁𝗶𝘃𝗲 𝗗𝗮𝘁𝗮 𝗧𝘆𝗽𝗲𝘀
TypeScript lets you manage how you assign data to variables. You have two main ways to do this.
Explicit assignment You tell TypeScript exactly what type a value is. Example: let str: string = "hello";
Implicit assignment TypeScript guesses the type based on the value. This is called inferred typing. Example: let str = "hello";
Even with inferred typing, TypeScript protects your code. If you try to change a string to a number, TypeScript shows an error.
When should you use explicit assignment?
- When you declare a variable without a value immediately.
- For function inputs and outputs.
- Inside object interfaces.
- Inside classes.
TypeScript uses duck typing for complex objects. If an object matches a specific structure, TypeScript uses that structure. It will not let you add new properties that do not exist in the original definition.
JavaScript primitive types in TypeScript:
- number: Supports integers, decimals, hex, binary, and scientific notation.
- bigint: Used for very large integers.
- string: A sequence of characters.
- boolean: true or false.
- symbol: Creates unique values.
- null: Represents an empty or non-existent value.
- undefined: A placeholder for a variable without a value.
Note on null and undefined: If you do not set a type, these values allow a variable to change to any type. If you explicitly set the type to null or undefined, the variable stays that type.
Source: https://dev.to/jsha/introduction-to-typescript-javascript-primitive-data-types-49ok