TypeScript Simple Types
TypeScript supports some simple types (primitives).
18th August 2022
Time to read: 1 min
There are three main primitives in JavaScript and TypeScript:
boolean
- true or false valuesnumber
- whole numbers and floating point valuesstring
- text values like "TypeScript Rocks"
Type Assignment
When creating a variable, there are two main ways TypeScript assigns a type:
- Explicit
- Implicit
Explict Type
Explicit - writing out the type:
let firstName: string = "Dylan";
Implicit Type
Implicit - TypeScript will "guess" the type, based on the assigned value:
let firstName = "Dylan";
Error In Type Assignment
TypeScript will throw an error if data types do not match.
let firstName: string = "Dylan"; // type string
firstName = 33; // attempts to re-assign the value to a different type
let firstName = "Dylan"; // inferred to type string
firstName = 33; // attempts to re-assign the value to a different type
Unable to Infer
TypeScript may not always properly infer what the type of a variable may be. In such cases, it will set the type to 'any' which disables type checking.
// Implicit any as JSON.parse doesn't know what type of data it returns so it can be "any" thing...
const json = JSON.parse("55");
// Most expect json to be an object, but it can be a string or a number like this example
console.log(typeof json);
This behavior can be disabled by enabling noImplicitAny
as an option in a TypeScript's project tsconfig.json
.