Crash post on typescript
Vivekraj K R
Senior Front end developer(Human) | Software consultant(Human) | AI/ML enthusiast | Investor
Typescript is taking the front-end industry like a storm and lot of team has started adapting to typescript for their projects. So I think it's high time for us javascript developers to learn typescript. This post is completely aim to scratch the surface of typescript. Before diving to this post, you should have some knowledge in data type mechanism in javascript. If you have the habit of learning the stuffs in micro packages, this is gong to be an introduction to the typescript world. Let's get started!
Basic typescript syntax
This is the basic syntax for defining type for a variable. A variable name followed by a full colon and then the data type of the expected value for that particular variable. The 'any' type will absolve all the type definitions. We can pass any values to it. But that's not the point of using typescript.
let a: any;
let x: number
let y: string;
let z: string[];
a = "literally anything";
x = 10;
y = "Hello";
z = ["Apple", "Orange"];
Custom types with interfaces
We can declare our own custom data types with interface by following the below syntax. Heres an example of object containing contact details. If the primaryContact object doesn't satisfy the required fields or the defined types for the values, the typescript is gonna throw warnings. And the question mark denotes the optional filed. It's an explicit exemption.
interface Contact {
? name: ContactName,
? age: number,
? dob: Date,
? pets: string[],
? location?: string
}?
const primaryContact: Contact = {
name: "John",
age: 25,
dob: new Date("10-11-1996"),
pets: ["Rocky"],
}
Type aliases
We can create aliases for the existing types by adding type keyword in front of any string and assigning a data type. And use that as a type definition as I mentioned earlier.
type ContactName = string;
type Status = boolean;
let name: ConactName = "John";
Enumerable types
Just like a javascript object! The usage is simple just access any member as a property off of the enum itself, and declare types using the name of the enum.
enum ContactStatus {
? New = "new",
? Active = "active",
? Inactive = "inacive"
}
let new = ContactStatus.New;
Typing functions
We can define the types for the values returned by the function and at the same time type for the argument that function expects.
const cloneObj = (source: Contact): Contact => {
? return Object.assign({}, source);
}
Meta types using generics
Generic types can be used to capture the type of argument which is being passed to the function and hold that type in a generic variable by this syntax <T>. 'T' can be any string but it's the typical name for generics.
领英推荐
const printValue = <T,>(name: T) => {
? console.log(name);
}
printValue(12);
printValue("John");
Multiple types with union types
What if we want to bound certain variables to multiple type. Can be achieved by using union. The pipe ("|") symbol allows us to declare multiple types for the same variable.
type BirthDate = string | number | Date;
let birthday:BirthDate? = "10-11-1992"; //
Keyof operator
Remember the interface syntax? We can bound a variable's type by the type of the keys of already declared interface.
type ContactField = keyof Contact;
const name: ContactField = "John"; //Won't be available at runtime.
Typeof operator
We can make use of javascript's typeof operator. Simply put 'typeof' of a variable while assigning type to another variable.
const myType = {min: 1, max: 100};
const save = (source: typeof myType) => {};
Indexed access type
Just like accessing a property of object. We can pull the type of a property of an interface that already declared.
type nametype = Contact["name"];
const name: nametype = "John";
Limited types with records
We can limit the types by using Record keyword by combining union operator as follows.
let user: Record<string, number | string | Function> = { name: "John", age: 25 }
user = 123; //completely new type, throws error;
Thats the end of this post. However, This post haven't covered how to install and config ts. And other features like decorators and global type definition. I'll leave it you to explore further.