We’ve already seen the standard data types in JavaScript and TypeScript. However, JavaScript allows for class, and we want to therefore be able to define a data-type within TypeScript.
Since JavaScript supports classes and object-oriented programming, so does TypeScript. You can explicitly describe this object’s shape using an interface
declaration.
interface Student {
stuNum: number;
name: string;
major: string;
active: boolean;
}
Then, to define an object of this type, we can just use:
const student1: Student = {
stuNum: 1234,
name: "Bruce Wayne",
major: "Criminal Justice",
active: true
};
This allows us to make sure we are using all the right types, as well as the correct properties. However, if we miss type in a property name, we’ll see and error.
const student2: Student = {
stuNum: 3579,
studentName: "Clark Kent",
major: "Journalism",
active: true
};
Notice studentName. It is not found in our interface, and therefore will generate an error letting us know we’ve created an issue. Specifically we’ll get an: Object literal may only specify known properties, and 'studentName' does not exist in type 'Student'.
Now, we can do the same if we want to define a class. However, there is a little bit of difference as we don’t put the interface
on the class definition, but when we create the object. Here we can define our properties as we normally would in a JavaScript class, but we can add data types.
class StudentAccount {
stuNum: number;
name: string;
major: string;
active: boolean;
constructor(studentNumber, name, major, active = true) {
this.stuNum = studentNumber;
this.name = name;
this.major = major;
this.active = active;
}
}
Then we use the interface to ensure it works correctly when we create our object.
let myStudent:Student = new StudentAccount(9876,'Lois Lane','Business Management');
Composing Types
You can also compose a variable, that is, with TypeScript, you can create complex types by combining simple ones. There are two popular ways to do so: unions and generics.
To use a Union, you will use a | character to limit values.
type color = "red" | "blue" | "green";
let exteriorPaint: color = "blue"; // this is OK
let interiorPaint: color = "black"; // this is an error
In this way, we are creating a type, and specifying potential values. We don’t even have to have the same data type for all the values, but we have to be careful in how we would handle something like that, and that is beyond the scope of what we are talking about here.
Generics is something worth looking at later if necessary. We’re going to stay simple.
Custom Data Types in TypeScript was originally found on Access 2 Learn