Basic types
1. any
Use if you are completely out of options.
basically typescript will not throw any error for type any.
const a : any;
2. unknown
Unknown is like any but with restrictions. You can't perform any action with unknown type unless you convince typescript that the type is of specific type.
Things to remember ==>
TypeScript will never infer something as unknown . you have to explicitly annotate it.
You can compare values to values that are of type unknown.
let a: unknown = 30;
if(a!=9) { //true
}
- But, you can’t do things that assume an unknown value is of a specific type you have to prove to TypeScript that the value really is of that type first.
let a: unknown = 30;
let c = a +90; //Error 'a' is of type 'unknown'.
if (typeof a === 'number') { //true
let d = a+20; //valid
}
3. boolean
The Boolean type has two values: true and false. You can compare them (with, =
, ===
||, &&, and ?), negate them (with !), and not much else. Use Boolean like this:
let a = true // boolean (a)
var b = false // boolean (b)
const c = true // true (c)
let d: boolean = true // boolean (d)
let e: true = true // true (e)
let f: true = false // Error TS2322: Type 'false' is not assignable to type true (f)
This example shows a few ways to tell TypeScript that something is a boolean:
- You can let TypeScript infer that your value is a boolean (a and b).
- You can let TypeScript infer that your value is a specific boolean (c).
- You can tell TypeScript explicitly that your value is a boolean (d).
- You can tell TypeScript explicitly that your value is a specific boolean (e and f)
🚨Special const
Notice how const type is inferred at (c). You don't have to specify types for const as it gets infer by typescript. Also you have to initialize const declaration in typescript otherwise it will throw an error.
const d; //Error 'const' declarations must be initialized
const c = true; //infer as true
🚨Type literal
Notice how we used boolean true as type in (e). This is called type literal. By definition it means -
A type that represents a single value and nothing else.
let e: true = true // true (e)
4. number
number is the set of all numbers: integers, floats, positives, negatives, Infinity, NaN,
and so on. Numbers can do, well, numbery things, like addition (+), subtraction (-),
modulo (%), and comparison (<). Let’s look at a few examples:
let a = 1234 // number
var b = Infinity * 0.10 // number
const c = 5678 // 5678
let d = a < b // boolean
let e: number = 100 // number
let f: 26.218 = 26.218 // 26.218
let g: 26.218 = 10 // Error TS2322: Type '10' is not assignable to type '26.218'.
5. bigint
bigint is a newcomer to JavaScript and TypeScript: it lets you work with large inte‐
gers without running into rounding errors. While the number type can only represent
whole numbers up to 253, bigint can represent integers bigger than that too. I supports all arithmetic operations. It does not support floating point numbers.
let a = 1234n // bigint
const b = 5678n // 5678n
var c = a + b // bigint
let d = a < 1235 // boolean
let e = 88.5n // Error TS1353: A bigint literal must be an integer.
let f: bigint = 100n // bigint
let g: 100n = 100n // 100n
let h: bigint = 100 // Error TS2322: Type '100' is not assignable to type bigint
6. object
let a: {b: number} = {
b: 12
}
here {b: number} is the shape of the object and after = is the actual value of the object.
[!NOTE] Optional Fields ?
By default all fields in object type are required . You can define an optional field by " ? ".
let a: {b: number; c?:boolean}
a={b: 144} //ok even without c
[!NOTE] Index Signatures
you can define object keys type in Index Signatures format like below
let a: {b: number,[key:number]:boolean} = {
b: 12
}
Note that this key is not compulsory but optional meaning you can define a without such key like
a = {
b: 12
}
But if you define a key with number as key then you have to follow the object structure of
[ key:number ]:boolean
a = {
b: 12
10:true //ok
10:'sdf' //Error
}
🚨 IMP : only string, number, symbol are assignable as key type.
[!NOTE] Read-only fields
Use "readonly" keyword for defining a object field as read-only.
let user: {
readonly firstName: string
} = {
firstName: 'abby'
}
user.firstName // string
user.firstName =
'abbey with an e' // Error TS2540: Cannot assign to 'firstName' because it
// is a read-only property.
[!NOTE] Empty object types {}
Every type except null and undefined—is assignable to an empty object type, which can make it
tricky to use. Try to avoid empty object types when possible:
let danger: {}
danger = {}
danger = {x: 1}
danger = []
danger = 2
7. arrays
let a = [1, 2, 3] // number[]
var b = ['a', 'b'] // string[]
let c: string[] = ['a'] // string[]
let d = [1, 'a'] // (string | number)[]
const e = [2, 'b'] // (string | number)[]
let f = ['red']
f.push('blue')
f.push(true) // Error TS2345: Argument of type 'true' is not
// assignable to parameter of type 'string'.
let g = [] // any[]
g.push(1) // number[]
g.push('red') // (string | number)[]
let h: number[] = [] // number[]
h.push(1) // number[]
h.push('red') // Error TS2345: Argument of type '"red"' is not
// assignable to parameter of type 'number'.
8. Tuples
Tuples are subtypes of array. They’re a special way to type arrays that have fixed
lengths, where the values at each index have specific, known types. Unlike most other
types, tuples have to be Explicitly Typed when you declare them Typescript will NOT infer them.
let a: [number] = [1]
// A tuple of [first name, last name, birth year]
let b: [string, string, number] = ['malcolm', 'gladwell', 1963]
b = ['queen', 'elizabeth', 'ii', 1926] // Error TS2322: Type 'string' is not
// assignable to type 'number'.
Tuples also support "rest" operator,
// A list of strings with at least 1 element
let friends: [string, ...string[]] = ['Sara', 'Tali', 'Chloe', 'Claire'] //a
// A heterogeneous list
let list: [number, boolean, ...string[]] = [1, false, 'a', 'b', 'c'] //b
a - means tuples can have one string element and rest all the elements should have type "string"
they can have any number of length.
[!NOTE] Read-only Arrays and Tuples
let as: readonly number[] = [1, 2, 3] // readonly number[]
let bs: readonly number[] = as.concat(4) // readonly number[] //concat does not mutate as original arrray
let three = bs[2] // number
as[4] = 5 // Error TS2542: Index signature in type
// 'readonly number[]' only permits reading.
as.push(6) // Error TS2339: Property 'push' does not
// exist on type 'readonly number[]'
let r:readonly [number,string] =[12,"test"]//readonly [number,string]
r[0] = 334; // Cannot assign to '0' because it is a read-only property
Difference between Read-only Array and Read-only tuple
Feature | Readonly Array | Readonly Tuple |
---|---|---|
Purpose | Represents a collection of elements of the same type that should not be modified. | Represents a fixed-size collection of elements, where each element may have a different type, and the structure should not be modified. |
Size | Can be of any length. | Has a fixed length defined by its type. |
Type of Elements | All elements must be of the same type. | Elements can be of different types. |
Use Cases | Useful when you need to pass an array to a function and ensure that the function doesn't modify it. | Useful when you need to represent a fixed set of values with known types, such as coordinates (x, y) or RGB colors. |
Syntax |
readonly T[] or ReadonlyArray<T>
|
readonly [T1, T2, ...] |
9. null, undefined, void, and never
Type | Meaning |
---|---|
null | null Absence of a value |
undefined | undefined Variable that has not been assigned a value yet |
void | void Function that doesn’t have a return statement |
never | never Function that never returns |
10. Never type
The never type in TypeScript represents values that will never occur. It's used in situations where a function will never return or a variable can never hold a value.
note :
- No type is a subtype of, or assignable to, never (except never itself).
- Even any isn't assignable to never.
Use-case : exhaustive type checking in switch case
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; sideLength: number };
function getShape(shape: Shape): void {
switch (shape.kind) {
case "circle":
console.log("circle");
break;
case "square":
console.log("square");
break;
default:
//if we forgot to include any case from Shape type then we will get below error.
let exau: never = shape; // Error -Type '{ kind: "square"; sideLength: number; }' is not assignable to type 'never'.
return exau;
}
}
11. Enums
Think of them like objects where the keys are fixed at compile time, so TypeScript can check that the given key actually exists when you access it.
There are ONLY two kinds of enums: enums that map from strings to strings, and enums
that map from strings to numbers. They look like this:
//mapped to NUMBERS
const enum Language {
English,
Spanish,
Russian
}
console.log(Language.English); //0
console.log(Language.Spanish); //1
console.log(Language.Russian); //3
//Notice they are auto-incrementing
//mapped to strings
//Notice = NOT : like object
const enum Language {
English='English',
Spanish='Spanish',
Russian='Spanish',
}
console.log(Language.English); // English
console.log(Language.Spanish); //Spanish
you can access enums by keys only.
const enum Color {
Red = '#c10000',
Blue = '#007ac1',
Pink = 0xc10050, // A hexadecimal literal
White = 255 // A decimal literal
}
//By Key
let a = Color.Red // Color
let b = Color.Green // Error TS2339: Property 'Green' does not exist
// on type 'typeof Color'.
console.log(Color[0]) // Error: A const enum member can only be accessed using a string literal.
In Number type enum values are auto-incrementing. if you start a member by 99 then next will be 100 even if you do not explicitly define.
enum Color {
Red = 99,
Pink
}
console.log(Color.Pink); // 100
Use-case
enum APIstatus {
NOT_FOUND=404,
BAD_REQUEST=400,
INTERNAL_SERVER_ERR=500,
OK=200,
FORBIDDEN=403
}
function printError (errStatus:APIstatus) // here enum is used as type.
{
console.log("Request Failed with staus code",errStatus)
}
printError(APIstatus.NOT_FOUND); // here enum used as value i.e, 404
printError(500);
printError(201);//Argument of type '201' is not assignable to parameter of type 'APIstatus'.
Top comments (0)