javascript - typescript - overview

TypeScript

Développé par Microsoft

C'est un sur-ensemble de JavaScript (c'est-à-dire que tout code JavaScript correct peut être utilisé avec TypeScript). Le code TypeScript est transcompilé en JavaScript, pouvant ainsi être interprété par n'importe quel navigateur web ou moteur JavaScript.

auteurs / contributeurs

Anders Hejlsberg (fr) (github profile)

Author of Turbo Pascal, chief architect of Delphi, lead architect of C#, conceptor of .NET framework and core developper and conceptor of TypeScript.

Daniel Rosenwasser

Program Manager of TypeScript

Ryan Cavanaugh

TypeScript lead dev

Mohamed Hegazy

TypeScript dev (retired)

articles

TypeScript lead dev Ryan Cavanaugh about TypeScript and OOP :

"I'm using TypeScript so I have to write OOP code with classes" :: "I got a paintbrush from Home Depot so I have to paint my house orange"

documentation

tsconfig.json

tsconfig.json official doc - www.typescriptlang.org

tsconfig.json schema on json.schemastore.org

TypeScript Configuration - angular.io/guide

compiler options

--noImplicitAny

See noImplicitAny in TypeScript Deep Dive from basarat.gitbooks.io

By default this option is set to false.

When a type is not defined by the programmer and when it is impossible to infer it, TypeScript infers an any type, example :


function log(someArg) {
  sendDataToServer(someArg);
}

// What arg is valid and what isn't?
log(123);
log('hello world');

When set to true, the compiler raises an error in that case.

It forces the programmer to explicitly set the type and at least the any type which in fact remove type checking (it allows anything).

--strictNullChecks

See Nullable Types section in Advanced Types from TS official handbook

See Should I use the strictNullChecks TypeScript compiler flag - yes or no? - www.tsmean.com/articles

Introduced in TS 2.0.

By default this option is set to false for retro compat purposes.

In JavaScript and without this option in TypeScript, undefined and null are assignable to anything. We can do this :


let toto = 'toto';
toto = null;

Or in TypeScript :


let toto: string = 'toto';
toto = null;

With this is option set to true, it is not possible anymore.

The intent is to avoid null pointers exceptions.

If the option is set, the programmer needs to explicitly declare when a value can be undefined or null like this :


let toto: string | null = 'toto';
toto = null;

toto = undefined; // Still raise error, should have declare toto as 'let toto: string | null | undefined;'

optional parameters

If the option is set and an optional parameter is used, the type is implicitly considered to be an union with undefined :


function f(x: number, y?: number) {
    return x + (y || 0);
}
f(1, 2); // OK
f(1); // OK
f(1, undefined); // OK
f(1, null); // error, 'null' is not assignable to 'number | undefined'

declaration files

Introduction - www.typescriptlang.org/docs/handbook

Consumption of *.d.ts files - www.typescriptlang.org/docs/handbook

install a @types/<lib> package or if the lib itself include a "types" prop in its package.json it's already there.

See DefinitelyTyped @ github.com for @types consumption and TS publishing doc for "types" prop.

Ex : Node.js typings are there.

Ambient Declarations - basarat.gitbooks.io/typescript

How do you produce a .d.ts “typings” definition file from an existing JavaScript library? - stackoverflow.com - 20121019

Getting started with TypeScript type definitions - medium.com/@jonjam - 20171113

How to create your own TypeScript type definition files (.d.ts) and contribute to DefinitelyTyped on GitHub - blog.wolksoftware.com - 20161015

tools

dts-gen - github.com/Microsoft

best practices

TSLint

tslint - palantir.github.io

TSLint command-line interface

TSLint rules list

videos

  • TypeScript, le JavaScript statiquement typé : Devoxx2015

    Migration progressive (passer les .js en .ts suffit à migrer sur typescript et inversement pour rollback)

    Facilité apprentissage (juste le fait de typer)

    Compatible ES6 (ajoute des polyfills, 90% de babel, donc autant faire ES5 -> typescript plutôt que ES5 -> ES6 -> TS

    Refactoring simplifié du fait des types (erreurs à la compilation)

    Assitance IDE meilleure (Webstorm nickel)

erreurs tscompiler

errors codes classification :

Diagnostics are categorized into general ranges. If adding a new diagnostic message, use the first integral number greater than the last used number in the appropriate range.

1000 range for syntactic messages 2000 for semantic messages 4000 for declaration emit messages 5000 for compiler options messages 6000 for command line compiler messages 7000 for noImplicitAny messages

Erreurs courantes après migration ES5/ES6 vers TS

  • TS2339: Property 'xxx' does not exist on type 'Yyyy'.

Cf issue 6373 : Getting error TS2339: Property does not exist on type for a valid ES6 class

Cf issue 2606 : ES6 should be valid TypeScript

class Car {
    constructor(weight) {
        this.weight = weight;
    }
}

is invalid ts code, it will output Error:(3, 14) TS2339: Property 'weight' does not exist on type 'Car'.

class Car {
    weight: number;

    constructor(weight: number) {
        this.weight = weight;
    }
}

is required by TS.

Anyway it is a non-blocker to generate the target javascript bundle.

If the input code is syntactically correct (prior to type checking) then it can generate ES output, and it is "valid" TS. At this first level, TS is a superset of ES, in that the set of valid TS programs is larger than the set of valid ES programs (because it includes all the valid ES programs plus those with type annotations).

The second level is type-correctness, which is what your error is complaining about. At this level, TS can act as a subset of ES: some valid ES programs, such as your example, are not type-correct TS programs.

  • error TS2380: 'get' and 'set' accessor must have the same type.

See TypeScript/issues/4087 and TypeScript/issues/2521

A classical pattern in JS with class to define a model is :

class MyClass {
    constructor(value) {
        this._myDate = value;
    }

    get myDate() {
        return this._myDate;
    }

    set myDate(value) {
        this._myDate = moment(value);
    }
}

The accessors are used to refine / format the data set to the instance.

But in TypeScript accessors must have the same type, and when converted to TS the compiler raise an error :

class MyClass {

    private _myDate: moment.Moment;

    get myDate(): moment.Moment {
        return this._myDate;
    }

    set myDate(value: Date | moment.Moment) {
        this._myDate = moment(value);
    }
}

The workaround is to create a dedicated function but we loose the instance.myDate = new Date(); usage.

class MyClass {

    private _myDate: moment.Moment;

    get myDate(): moment.Moment {
        return this._myDate;
    }

    set myDate(value: moment.Moment) {
        assert.fail('Setter for myDate is not available. Please use: setMyDate() instead');
    }

    setMyDate(value: Date | moment.Moment) {
        this._myDate = moment(value);
    }
}

Another workaround would be to type _myDate with Date | moment.Moment but we loose a lot of type checking here.

See cons TS2380 rule arguments :

juanpablodelatorre

When TypeScript limits JavaScript, it becomes more of a nuisance than an advantage. Isn't TypeScript meant to help developers communicate with each other?

Also, setters are called Mutators for a reason. If I wouldn't need any kind of conversion, I wouldn't use a setter, I would set the variable by myself.

gmurray81

impact with Angular and components inputs from templates.

See pros TS2380 rule arguments :

kitsonk (TypeScript contributor)

IMO, ever since JavaScript allowed accessors, people have potentially created confusing APIs with them. I personally find it confusing that something on assignment magically changes to something else. Implicit anything, especially type conversion, is the bane of JavaScript IMO. It is exactly the flexibility that causes problems.

mhegazy (TypeScript contributor)

After thinking about this some more. i think the issue here is really the complexity of the implementation.

He flagged issue as "Too Complex" and "Design Limitation" labels after that post then closed the issue 2521.

kitsonk (TypeScript contributor)

The labels on the issue indicate it is a design limitation and the implementation would be considered too complex, which essentially means that if someone has a super compelling reason why this should be the case, it is not going anywhere.

features

conditional types

Added in TypeScript 2.8 see release notes.

Super nice answer here

Conditional types probably aren't something you'll write every day, but you might end up using them indirectly all the time. That's because they're great for 'plumbing' or 'framework' code, for dealing with API boundaries and other behind-the-scenes kinda stuff.

results for ""

    No results matching ""