// extending a typetypeCat=Animal& { color:string;};
// value with 2 typestypeID=string|number;constuserId:ID=239053;constitemId:ID="A934VL";
InterfacesAn interface declaration is another way to name an object type. Interfaces support a more convenient extension and are used more often.
interfaceIPerson { firstName:string; lastName?:string; // an optional parameter gender:"female"|"male"; // only certain values isMarried:boolean;}//Extending an interfaceinterfaceIWorkerextendsIPerson { job:string;}constsomeone:IWorker= { firstName:"Alex", gender:"male", isMarried:true, job:"engineer",};
Functions
Basic usageWe can describe the types of function arguments as well as the return value
// type "void" means that our function does not return anythingfunctionlogInfo(name:string, age:number):void {console.log(`My name is ${name}, I'm ${age} y.o.`);}// Arrow functionconstsquare= (x:number):number=> x * x;
Default argumentsWhen default parameters are specified, their types are automatically determined by the passed values
ModifiersVarious modifiers allow you to define the scope of variables and methods
classExample {constructor(a:number, b:number) {this.a = a;this.b = b; }/* prevents assignments to the field outside of the constructor */readonly a:number;/* visible only inside classes inherited from the current class (not from outside) */protected b:number;/* visible only inside current class (not from inherited and outside) */private secret ="hello";alert= () => {};}
Extending a classClasses can easily be extended by adding new variables/methods. This also supports overriding methods, but in a way that ensures backward compatibility.
enumBool { yes ="YES", no ="NO"}enumServer { host ="server.com" port =5432}
Generics
Basic usageGenerics allows to create a component that can work over a variety of types rather than a single one
functiontest<T>(value:T):T {return value;}// "T" will be replaced by the type we specifiedtest<string>("Hello World");test<number>(2022);test<boolean>(true);
Type checkingYou can safely use type checking with the typeof operator to execute the appropriate logic
functionlogger<T>(value:T):void {if (typeof value =="string") {// we are pretty sure that only strings will get hereconsole.log(value.toLocaleUpperCase());// therefore, we can use string methods } elseif (typeof value =="number") {console.log(value.toFixed(2)); } else {console.log(`${value} has the ${typeof value} type`); }}logger<string>("Hello World"); // "HELLO WORLD"logger<number>(2022); // 2022.00logger<boolean>(true); // "true has the boolean type"
Multiple genericsYou can pass multiple generics, for example, to describe different input and output types in functions