Skip to content

ufocoder/wtfts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 

Repository files navigation

wtfts

Tricky and non obvious TypeScript Examples

👋🏻 Welcome to add new trick examples or to improve old one

Table of Contents

Enum option

TypeScript code:

const optionA = 'variableValueA';

enum CustomEnum {
    optionA = 'enumValueA',
    optionB = optionA
}

// CustomEnum.optionB !== optionA

Playground

Explanation:

Value for optionB use optionA from enum score.

Will be compiled to:

"use strict";
const optionA = 'variableValueA';
var CustomEnum;
(function (CustomEnum) {
    CustomEnum["optionA"] = "enumValueA";
    CustomEnum["optionB"] = "enumValueA";
})(CustomEnum || (CustomEnum = {}));

Invariant

The following code will be compiled without errors:

interface Animal { name: string }
interface Cat extends Animal { meow: () => string }
interface Dog extends Animal { wow: () => string }

const addAnimal = (animals: Animal[]) => {
    const cat: Cat = { name: 'Cat #1', meow: () => 'meow' };
    animals.push(cat);
}

const dogs: Dog[] = [];

addAnimal(dogs);

dogs[0].wow()

Playground

Comparing two functions

let x = (a: number) => a;
let y = (b: number, s: string) => s ? b : 0;

y = x; // OK
x = y; // Error

Playground

Explanation from official documentation

Interface redeclaration

The following code:

interface Box {
    size: number;
    color: string;
}

// .. many lines of code here

interface Box {
    weight: number;
}

const box: Box = {
    weight: 5
}

has compile error:

Type '{ weight: number; }' is missing the following properties from type 'Box': size, color

Playground

Explanation: Interfaces not are overridden by new declations.

Interfaces with similar structure

interface Entity {
  name: string;
}


interface Enemy {
  name: string;
  health: number;
  attack: number;
}

interface Player {
  name: string;
  health: number;
  attack: number;
}

let entity: Entity = { name: 'Mario' }
let enemy: Enemy = { name: 'Shredder', health: 100, attack: 20 };
let player: Player = { name: 'John Cena', health: 110, attack: 35 };

enemy = player; // OK ?!
player = enemy; // OK ?!

entity = enemy; // OK ?!
enemy = entity; // Error

Playground

Explanation: TypeScript is based on structural subtyping

About

Tricky TypeScript Examples

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published