magic types

let's dive into TS type system

Michał Michalczuk

michalczukm.xyz

Michał Michalczuk

Senior JavaScript Developer

Ciklum / Stibo Systems

 

 

IT trainer

infoShare Academy

                     magic types

let's dive into TS type system

Michał Michalczuk

michalczukm.xyz

TypeScript

  • JavaScript that scales
     
  • Superset of JavaScript that compiles to plain JavaScript
     
  • JavaScript code is legal TypeScript
     
  • Optional static typed language

 

TypeScript

ES6

ES5

TypeScript type system

  • Optional static typed
     
  • Structural type system
     
  • As strict as you want to
     
  • Rich

Type systems

What problems they solve?

Imagine this code ...

I know 

The "f... the logic" version

function getValue() {
    switch(Math.floor(Math.random() * 10) % 3) {
        case 0:
            return 'foo';
        case 1:
            return 5;
        case 2: 
            return { value: '5' };
        default:
            throw new Error('Ups');
    }
}

const result = getValue() + 1;

Ok. I'll use
and it will be good!

I know 

The "f... the logic" version

function getValue(): any {
    switch(Math.floor(Math.random() * 10) % 3) {
        case 0:
            return 'foo';
        case 1:
            return 5;
        case 2: 
            return { value: '5' };
        default:
            throw new Error('Ups');
    }
}

const result = getValue() as number + 1;

You get the point.

is not magic wand

How type systems divide?

Type systems

Lang Types check Run time safety



 
Dynamic Weak



 
Static Weak



 
Static Strong

In                  we have no guarantee for types during runtime

What about casting?

type Order = {
    clientName: string
};

const orderWorks = {} as Order;

const orderAlsoWorks = <Order>{};

Sorry, its not casting

Its Type Assercion

You tell compiler:

I'm sure of the type, hold my bear

has structural type system

 

What it means?

Structural

Nominal


type Foo = {
    foo: string;
    handleStuff: () => void;
}

type Bar = {
    foo: string;
}

const foo: Foo = { 
    foo: 'foo', 
    handleStuff: () => ({}) 
};

// works, struc. of `Bar` is subset
const bar: Bar = foo;

// won't compile. 
// `handleStuff` is missing
foo = bar;
class Foo {
    public string Foo { get; set; }
}

class Bar {
    public string Foo { get; set; }
}


Foo foo = new Foo { Foo = "foo" };

// won't compile.
// Its different type
Bar bar = foo;

TS Interesting example

function handle( item: {value: string} ) {
    // do stuff
}

handle({ 
    value: 'some value' 
});


const item = {
    name: 'Item name',
    value: 'some value',
};

handle(item);

Works

But

function handle( item: {value: string} ) {
    // do stuff
}

// [error] Object literal may only specify known properties, 
// and 'name' does not exist 
// in type '{ value: string; }'.
handle({
    name: 'Item name',
    value: 'some value',
});

Error

Interface

vs 

Class

vs

Type alias

What to choose?

Class when need to
  • instantiate
  • handle state
  • have implementation
 
Interface/Type aliases when need to
  • describe contract

  • do anything else

Interfaces or Type aliases?

As we mentioned, type aliases can act sort of like interfaces; however, there are some subtle differences.

Interfaces vs Type aliases

Interface when
  • we'll have actual implementations
  • want to merge declarations
  • creating public API definition
Type aliases when 
  • everything else

String/Numeric unions

vs 

Enums

Enums are values

enum StringEnum {
    One = 'One', 
    Two = 'Two'
}
enum NumericEnum {
    One,
    Two
}
var StringEnum;
(function (StringEnum) {
    StringEnum["One"] = "One";
    StringEnum["Two"] = "Two";
})(StringEnum || (StringEnum = {}));
var NumericEnum;
(function (NumericEnum) {
    NumericEnum[NumericEnum["One"] = 0] = "One";
    NumericEnum[NumericEnum["Two"] = 1] = "Two";
})(NumericEnum || (NumericEnum = {}));
.ts
.js

Thats why you cannot put them in

.d.ts

Nullable and special types

Index types

Intersect and union types

Generics

Discriminated union types

Polymorphic this

Conditional types

Sum up

you can solve a lot problems on types level

In

Questions time

Feedback*

 

 

*thing which speakers need

Michał Michalczuk

michalczukm.xyz

Thank you!

michalczukm

TypeScript magic types - deep dive

By Michał Michalczuk

TypeScript magic types - deep dive

4Developers - 15.10.2018 Kraków; KarieraIT - 8.12.2018 Gdańsk

  • 1,982