Tricky and non obvious TypeScript Examples
👋🏻 Welcome to add new trick examples or to improve old one
- Enum option
- Invariant
- Comparing two functions
- Interface redeclaration
- Interfaces with similar structure
TypeScript code:
const optionA = 'variableValueA';
enum CustomEnum {
optionA = 'enumValueA',
optionB = optionA
}
// CustomEnum.optionB !== optionA
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 = {}));
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()
let x = (a: number) => a;
let y = (b: number, s: string) => s ? b : 0;
y = x; // OK
x = y; // Error
Explanation from official documentation
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
Explanation: Interfaces not are overridden by new declations.
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
Explanation: TypeScript is based on structural subtyping