Arrays and tuples
- array - collection of items (similar to JavaScript). In TypeScript we can specify what value types we expect for items to be:
let arr: number[] = [];
arr[0] = 1;
arr[0] += "string"; // Type 'string' is not assignable to type 'number'
we can declare nested arrays like this:
let arr: string[][] = [["string1"], ["string2"], []].
- tuples - fixed length array that has predefined types for each position:
let tup: [number, string] = [1, "text"];
tup[0] = 2;
tup[1] = 3; //Type 'number' is not assignable to type 'string'
We also can use nested tuples:
const coords: [number, number[]][] = [
[0, [0, 0]],
[10, [0, 1]]
];
coords[20] = [2, []];
Literal types
literal types - constraints on types (string, number or boolean), specifying exactly which values the variable is allowed to take:
let status: 'offline' | 'online';
status = 'ofline'; // Type '"ofline"' is not assignable to type '"offline" | "online"'. Did you mean '"offline"'?
Object literal
We can also specify what properties can our object have using object literals:
const obj: {
a: number,
b: string,
c?: boolean
} = {
a: 1,
b: 'text',
c: true
};
obj.b = 2; //Type 'number' is not assignable to type 'string'
We used optional parameter (
?:), that allows us to omit value assignment to the property.
enum type
enum (from enumeration) - a collection of named constants linked with an integer (by default enumeration starts from 0):
enum Color {
Red,
Green,
Blue
}
let colorName: string = Color[1];
console.log(colorName);
enum Colors {
Red = 2,
Green,
Blue
}
let colorName: string = Colors[3];
console.log(colorName); // Green
String enums
String enums allow us to create a set of constants mapped to strings:
enum Notification {
Warning = "This is a warning",
Success = "This is a success",
Danger = "This is a danger"
}
console.log(Notification.Danger); // This is a danger
enum as data type of a variable
enum Status {
Offline = 'OFFLINE',
Online = 'ONLINE'
}
let userStatus: Status;
userStatus = Status.Offline;
console.log(userStatus); // OFFLINE
enum vs object
You may ask yourself, why would we use enum, if we can achieve the same behavior with object?
Let's look at the last example: we have userStatus type as enum, but in the end of the day it's just a string and let's try to rewrite it with object:
const Status = {
Offline: 'OFFLINE',
Online: 'ONLINE'
}
let userStatus: string = Status.Offline;
userStatus = "plain text"; // OK
We can assign another value to
userStatus!
Actually the compiler transforms enum to javascript the object. We can even access its properties:
enum Status {
Offline = 'OFFLINE',
Online = 'ONLINE'
}
function getAttr(obj: {Offline: string}) {
return obj.Offline;
}
console.log(getAttr(Status)); // OFFLINE
Actually, we can make enums disappear at the compile time using const. They won't be compiled to the object and the variables assigned to their keys will be assigned to literals:
const enum Status {
Offline = 'OFFLINE',
Online = 'ONLINE'
}
let i: Status = Status.Offline;
function getAttr(obj: {Offline: string}) {
return obj.Offline;
}
console.log(getAttr(Status)); // 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.
Any, Unknown and Type Casts
- any - this type tells typescript compiler to ignore the variable while type checking. It means that we can assign any value to the variable and call any method on it:
let x: any;
x =1;
x=[2,3];
x(); // compiler allows it, since it doesn't know what type of the variable it is.
anyis used in a difficult situation, when we are not able to predict the type. Usually in the case of unceratainty you should useunknowntype.
- unknown - we don't know what the type is going to be but before performing any operations with the variable we have to check its type:
let a: unknown = 10;
if (typeof a === "number") {
a+=2;
}
console.log(a);
Another way to work with unknown type is to use type casting:
let a: unknown = 10;
// We tell the compiler to treat the variable as its type is number:
let b = (a as number) + 2;
console.log(b);
Top comments (0)