let myNumericVariable: number = 5;
let myString: string = 'hello';
let myArray: string[] = ['hello', 'hi'];
let myArray: Array<string> = ['hello', 'hi'];
function convertToUppercase(input: string): string {
return input.toUpperCase();
}
function createPerson(
id: number,
firstName: string,
lastName: string
): {id: number, name: string} {
return {
id,
name: `${firstName} ${lastName}`,
};
}
function add(a: number, b: number, c?: number) {
return a + b + (c ?? 0);
}
import { calculateSum } from './my-file';
let result: number = calculateSum([1,2,3])
export function calculateSum(numbers: number[]): number {
return numbers.reduce((a, b) => a + b)
}
import renamedSum from './my-file';
let result: number = renamedSum([1,2,3]);
export default function calculateSum(numbers: number[]): number {
return numbers.reduce((a, b) => a + b)
}
import * as add from './addition';
esModuleInterop=true
esModuleInterop=false
import add from './addition';
import lodash from 'lodash';
lodash.without([1,2,3], 2);
const people = [
{
id: 1,
name: 'Peter'
},
{
id: 2,
name: 'Rachel'
},
{
id: 3,
name: 'John'
},
{
id: 4,
name: 'Tim'
},
{
id: 5,
name: 'Zed'
}
];
const people = [
{
id: 1,
name: 'Peter'
},
{
id: 2,
name: 'Rachel'
},
{
id: 3,
name: 'John'
},
{
id: 4,
name: 'Tim'
},
{
id: 5,
name: 'Zed'
}
];
interface Person {
id: number;
name: string;
}
interface Person {
id: number;
name: string;
age?: number;
greet(name: string): string;
}
function createPerson(id: number, firstName: string, lastName: string)
: {id: number, name: string} {
return {
id,
name: `${firstName} ${lastName}`,
};
}
// becomes this:
interface Person {
id: number;
name: string;
}
function createPerson(id: number, firstName: string, lastName: string): Person {
return {
id,
name: `${firstName} ${lastName}`,
};
}
const people = {
martin: {
name: 'Martin',
age: 32
},
homer: {
name: 'Homer',
age: 50
}
}
console.log(item.martin.name)
console.log(item['martin'].name)
interface Person {
name: string;
age: number;
}
interface PeopleByName {
[key: string]: Person
}
let people: PeopleByName = {
martin: {
name: 'Martin',
age: 32
},
homer: {
name: 'Homer',
age: 50
}
}
console.log(item.martin.name)
console.log(item['martin'].name)
interface PrintFunction {
(text: string): void;
}
let printer: PrintFunction;
printer = (text) => console.log(text)
printer = (text) => console.error(text)
interface Person {
name: string;
age: number;
}
// Extending an interface
interface Employee extends Person {
employeeId: number;
}
interface Person {
name: string;
age: number;
}
// this extends Person
interface Person {
gender: string;
}
let calculator: Calculator = {...}
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayName() {
console.log(`My name is ${this.name}`);
}
}
class Animal {
constructor(public name: string) {
}
sayName() {
console.log(`My name is ${this.name}`);
}
}
let dog = new Animal('Lassie');
let mouse = new Animal('Mickey');
dog.sayName();
mouse.sayName();
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log(`Bark!`);
}
}
class Animal {
move(coordinates: Coordinates) {
this.coordinates = coordinates;
}
}
class Bird extends Animal {
isInTheAir: false;
move(coordinates: Coordinates) {
this.isInTheAir = true;
super.move(coordinates);
}
}
class Calculator {
// Overload signatures
add(a: number, b: number): number; // Add two numbers
add(a: string, b: string): string; // Concatenate two strings
add(a: number, b: number, c: number): number; // Add three numbers
// Single method implementation
add(a: unknown, b: unknown, c?: number): any {
if (typeof a === "number" && typeof b === "number") {
if (c !== undefined) {
return a + b + c;
}
return a + b;
}
if (typeof a === "string" && typeof b === "string") {
return a + b;
}
}
}
const calc = new Calculator();
console.log(calc.add(2, 3)); // Outputs: 5
console.log(calc.add("Hello, ", "World")); // Outputs: Hello, World
console.log(calc.add(1, 2, 3)); // Outputs: 6
class MathUtil {
static PI: number = 3.14159;
static calculateCircumference(radius: number): number {
return 2 * MathUtil.PI * radius;
}
}
console.log(MathUtil.PI);
MathUtil.calculateCircumference(3);
abstract class Shape {
abstract area(): number;
describe(): void {
console.log("This is a shape");
}
}
class Circle extends Shape {
constructor(public radius: number) {
super();
}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
type Person = {
name: string;
age: number;
}
type Answer = 'yes' | 'no';
let x: Answer;
type ToStringFn = (x: number) => string;
const toString: ToStringFn = (x: number) => `${x}`;
let value: number | string = 5; // ok
value = 'hi'; // also ok
let pet: Dog | Turtle | Cat;
type Square = {
type: 'square';
size: number;
};
type Circle = {
type: 'circle';
radius: number;
};
type Shape = Square | Circle;
const shape: Shape = await fetch('https://server');
if (isSquare(shape)) {
console.log(`Size is ${shape.size}`);
}
function isSquare(shape: Shape): shape is Square {
return shape.type === 'square';
}
type Answer = 'yes' | 'no';
type AnswerList = {
[key in Answer]: boolean;
}
const list: AnswerList = {
yes: true,
no: false
}
const obj = {
id: 1,
name: 'Martin'
}
type Person = typeof obj;
const obj2: Person = {
id: 2,
name: 'Lukas'
}
type Person = {
id: number;
name: string;
age: number;
};
// 'id' | 'name' | 'age'
const key: keyof Person = 'id';
type Person = {
id: number;
name: string
}
type Developer = {
os: 'Linux' | 'macOS' | 'Windows';
}
const someone: Person & Developer = {
id: 5,
name: 'George',
os: 'Linux'
}
let value: Array<number> = [5, 2, 4];
// generic function
function print<T>(item: T) {
console.log(item);
return item;
}
print<string>('hi');
let x = print(4); // x will be of type number
class Bucket<T> {
items: T[] = [];
insert(item: T) {
this.items.push(item);
}
}
let myBucket = new Bucket<string>();
myBucket.insert('hello');
type Person = {
name: string,
age: number;
}
type Age = Person["age"];
const obj: Record<string, number> = {
one: 1,
two: 2,
three: 3
};
type Person = {
name: string
};
const obj: Record<number, Person> = {
1: { name: 'Martin'},
2: { name: 'Lukas'},
};
interface Person {
age: number;
name: string;
}
let obj: Partial<Person> = {
age: 32
}
interface Person {
age: number;
name: string;
height: number;
}
let obj: Pick<Person, 'age' | 'name'> = {
age: 32,
name: 'Martin'
}
interface Person {
age: number;
name: string;
height: number;
}
let obj: Omit<Person, 'height'> = {
age: 32,
name: 'Martin'
}
type Animal = Dog | Turtle | Shark;
let obj: Exclude<Animal, Turtle>
// obj: Dog | Shark
type AdditionFn = (a: number, b: number) => number;
type Params = Parameters<AdditionFn>; // [number, number]
function add(a: number, b: number): number {
return a + b;
}
type Params = Parameters<typeof add>; // [number, number]
type Coords3d = {
x: number;
y: number;
z: number;
};
type Coords2d = {
x: number;
y: number;
};
type Sphere = {
coords: Coords3d;
};
type Circle = {
coords: Coords2d;
};
type Shape = Sphere | Circle;
function placeRandomly<T extends Shape>(
shape: T
): T extends Sphere ? Coords3d : Coords2d {
...
}
placeRandomly({ coords: { x: 1, y: 2 } });
function removeAge(obj) {
const { age, ...duplicateWithoutAge} = obj;
return duplicateWithoutAge;
}
function removeKey(obj, key) {
const duplicate = { ...obj };
delete duplicate[key];
return duplicate;
}
enum Status {
Success = 'SUCCESS',
Error = 'ERROR',
}
let requestStatus: Status = Status.Success;
type Person = {
name: string;
age: number;
greet(this: Person): void;
};
function sayHello(this: Person) {
console.log(`Hello, my name is ${this.name}`);
}
const person = { name: "John", age: 30 };
sayHello.call(person); // Hello, my name is John