TypeScript
TypeScript is JavaScript with syntax for types.
It is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
TypeScript is JavaScript with syntax for types.
It is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
let temperature = 20;
// wat is het type van deze variabele 'temperature' op lijn 1?
temperature = "warm";
// wat is nu het type van deze variabele?let temperature: number = 20;
// wat is het type van deze variabele 'temperature' op lijn 1?
temperature = "warm";
// TypeErrorJavaScript
TypeScript
let temperature = 20;
// Developer #10 schrijft de lijn hieronder
temperature = "warm";
// Maar heeft deze conversie over het hoofd gezien ...
const temperatureInFahrenheit = (temperature * 1.8) + 32;
// Bonus: wat is de waarde van temperatureInFahrenheit nu?TypeScript
cd my-empty-folder
npm init -y
npm install typescript --save-dev
npx tsc --init
npx tsclet temperature: number = 20;
let greeting: string = "Hello, students!";
let isThisCourseAwesome: boolean;function sum(a: number, b: number): number {
return a + b;
}function someFunc(): void {
console.log("Hi there!");
}type Address = {
name: string;
postalCode: string;
city: string;
street: string;
houseNumber: number;
};
async function sendMail(address: Address): void {
// some logic to send physical mail goes here ...
}
// What errors will the compiler throw here?
sendMail({
postalCode: "9000",
city: "Ghent",
street: "Leeuwstraat",
houseNumber: "1",
});// Who needs postal codes, right?
type Address = {
name: string;
postalCode?: string;
city: string;
street: string;
houseNumber: number;
};
async function sendMail(address: Address): void {
// some logic to send physical mail goes here ...
}
sendMail({
name: "Karel De Smet",
city: "Ghent",
street: "Leeuwstraat",
houseNumber: 1,
});function greeting(firstName: string, lastName?: string): void {
const nameToPrint = lastName ? `${firstName} ${lastName}` : firstName;
console.log(`Hello ${nameToPrint}!`);
}
// We can just greet people by their first name, the last name is optional
greeting("Karel");
greeting("Karel", "De Smet");function greet(name, greeting = 'Hello') {
console.log(greeting + ', ' + name);
}
greet("Karel");
// "Hello, Karel"
greet("John", "Hi");
// "Hi, John"// Basically the same as type Address from the previous slides
interface Address {
name: string;
postalCode?: string;
city: string;
street: string;
houseNumber: number;
};function sum(arr: Array<number>): number {
return arr.reduce((a: number, b: number) => {
return a + b;
}, 0);
}
// Array<number> en number[] betekenen exact hetzelfde,
// je kiest zelf welke syntax je verkiestconst arrayOfNumberOrString: Array<number | string> = [];
arrayOfNumberOrString.push(1);
arrayOfNumberOrString.push("Hello world");
// Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
arrayOfNumberOrString.push(false);const stringNumberTuple: [string, number] = ["Weeks from shore", 2];type Theme = "dark" | "light";
// Error: Type '"violet"' is not assignable to type 'Theme'.
const theme: Theme = "violet";Oefening 1:
Oefening 2:
Oefening 3:
User with the following properties:
username (string)email (string)age (number, optional)isActive (boolean)printUserInfo that takes a User objectOefening 4:
Product with properties name, price, and category. Define logical types for each property.Product objects and write a function getTotalPrice that calculates the total price of all products in the array.Oefening 5:
formatInput that takes a string or number as an argument.
TypeScript
let greeting = "Hello world";
// The TypeScript compiler infers that greeting is of type string.
// There's no need to make it explicit.
const arrayOfStudents = [];
// TypeScript can not know what type of values we will store in this array.
// So it infers this to be of type any[], which is almost never a good thing ...const to initialize a variable,// We know how to annotate the sum function in TypeScript
function sum(a, b) {
return a + b;
}
// But how do we annotate the add function?
function add(a) {
return function(b) {
return sum(a, b);
}
}
const addSeven = add(7);
console.log(addSeven(3));
// 10// Solution to the previous slide:
function sum(a: number, b: number): number {
return a + b;
}
function add(a: number): (b: number) => number {
return function(b: number) {
return sum(a, b);
}
}
const addSeven = add(7);
console.log(addSeven(3));
// 10/* JavaScript has first-class functions, so we can encounter them anywhere
e.g. in React props
Exercise: copy-paste this in the TypeScript playground
and add the missing interface */
interface Props {
// ?
}
const props: Props = {
onClick: () => console.log("Hi there!"),
onSave: (data: string) => doSomethingWithDataAndReturnBoolean(data)
}
function doSomethingWithDataAndReturnBoolean(data: string): boolean {
// This is just a mock implementation ...
return true;
}// Solution to the previous slide
interface Props {
onClick: () => void;
onSave: (data: string) => boolean
}
const props: Props = {
onClick: () => console.log("Hi there!"),
onSave: (data: string) => doSomethingWithDataAndReturnBoolean(data)
}
function doSomethingWithDataAndReturnBoolean(data: string): boolean {
// This is just a mock implementation ...
return true;
}let greeting: any = [];
// Since we annotated greeting with any, we can change the type later on
// to anything else: string, number, boolean, array, object ...
// We can also call any method on it, or access any property,
// even if that method or property does not exist
greeting.say();
greeting.toUpperCase();
// At compile time everything is OK. At run time, this will cause an error.let vAny: any = 10; // We can assign anything to any
let vUnknown: unknown = 10; // We can assign anything to unknown just like any
let s1: string = vAny; // Any is assignable to anything
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type
vAny.method(); // Ok; anything goes with any
vUnknown.method(); // Not ok; we don't know anything about this variable
// Source: https://stackoverflow.com/a/51439876function prettyPrint(x: unknown): string {
if (Array.isArray(x)) {
return "[" + x.map(prettyPrint).join(", ") + "]";
}
if (typeof x === "string") {
return `"${x}"`;
}
if (typeof x === "number") {
return String(x);
}
return "etc.";
}
// Source: https://blog.logrocket.com/when-to-use-never-unknown-typescript// What is the return type of the function below?
async function getSomeData() {
return fetch("https://some-data.com/api/data");
}// Answer to question on the previous slide
async function getSomeData(): Promise<Response> {
return fetch("https://some-data.com/api/data");
}TypeScript comes with a ton of built-in types
e.g. for promises, events ...
// What will be the return type of the function below?
function getSomePromise() {
return new Promise(() => {
return getRandomNumber();
});
}
function getRandomNumber(): number {
return Math.random();
}/* If we don't pass a type to the generic Promise constructor,
the Typescript compiler will infer it as Promise<unknown>.
The compiler is flawed here: it can't infer the Promise type (number).
*/
function getSomePromise(): Promise<unknown> {
return new Promise(() => {
return getRandomNumber();
});
}
function getRandomNumber(): number {
return Math.random();
}/*
But if we help the Typescript compiler out,
it can infer it as Promise<number>
*/
function getSomePromise() {
return new Promise<number>(() => {
return getRandomNumber();
});
}
function getRandomNumber(): number {
return Math.random();
}
TypeScript
function Button({ label, handleClick }) {
return <button className="btn btn-large whatever" onClick={handleClick}>{label}</button>;
}interface Props {
label: string;
handleClick: () => number;
}
function Button({ label, handleClick }: Props) {
return <button className="btn btn-large whatever" onClick={handleClick}>
{label}
</button>;
}
export default Button;