Présentation
TypeScript ajoute une vérification statique des types à JavaScript. Les exemples suivants contiennent des fragments de types indépendants et des points de suspension ; ils ne constituent pas un fichier source unique. Les assertions de type ne valident pas les données à l’exécution.
Types de base
any
void
boolean
number
string
null
undefined
bigint
symbol
string[] /* or Array<string> */
[string, number] /* tuple */
string | null | undefined /* union */
never /* unreachable */
unknown
enum Color {
Red,
Green,
Blue = 4
};
let c: Color = Color.Green
Déclarations
let isDone: boolean
let isDone: boolean = false
function add (a: number, b: number): number {
return a + b
}
// Return type is optional
function add (a: number, b: number) { ... }
Assertions de type
Variables
let len: number = (input as string).length
let len: number = (<string> input).length /* not allowed in JSX */
Fonctions
function object(this: {a: number, b: number}, a: number, b: number) {
this.a = a;
this.b = b;
return this;
}
// this is used only for type declaration
let a = object.call({ a: 0, b: 0 }, 1, 2);
// a has type {a: number, b: number}
Interfaces
Types en ligne
function printLabel (options: { label: string }) {
console.log(options.label)
}
// Note the semicolon
function getUser (): { name: string; age?: number } {
return { name: "Ada" };
}
Interfaces nommées
interface LabelOptions {
label: string
}
function printLabel(options: LabelOptions) { ... }
Propriétés facultatives
interface User {
name: string;
age?: number;
}
Propriétés en lecture seule
interface User {
readonly name: string
}
Signatures d’index
{
[key: string]: Object[]
}
Alias de types
Alias de types
type Name = string | string[]
Types d’intersection
interface Colorful { ... }
interface Circle { ... }
type ColorfulCircle = Colorful & Circle;
Types de fonctions
interface User { ... }
function getUser(callback: (user: User) => any) { callback({...}) }
getUser(function (user: User) { ... })
Classes
class Point {
x: number
y: number
static instances = 0
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}
Héritage
class Point {...}
class Point3D extends Point {...}
interface Colored {...}
class Pixel extends Point implements Colored {...}
Propriétés de paramètres
class Point {
static instances = 0;
constructor(
public x: number,
public y: number,
){}
}
Assertions d’affectation définie
class Point {
public someUselessValue!: number;
...
}
Génériques
class Greeter<T> {
greeting: T
constructor(message: T) {
this.greeting = message
}
}
let greeter = new Greeter<string>('Hello, world')
Modules
export interface User { ... }
Types d’accès indexé
interface Building {
room: {
door: string;
walls: string[];
};
}
type Walls = Building['room']['walls']; // string[]
L’opérateur keyof
type Point = { x: number; y: number };
type P = keyof Point; // x | y
Types conditionnels
// SomeType extends OtherType ? TrueType : FalseType;
type ToArray<T> = T extends any ? T[] : never;
type StrArrOrNumArr = ToArray<string | number>; // string[] | number[]
Inférence de types
type GetReturnType<T> = T extends (...args: any[]) => infer R
? R
: never;
type Num = GetReturnType<() => number>; // number
type First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;
type Str = First<['hello', 1, false]>; // 'hello'
Types littéraux
const point = { x: 4, y: 2 }; // { x: number, y: number }
const literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };
Types littéraux de gabarit
type SpaceChar = ' ' | '\n' | '\t';
type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;
type Str = TrimLeft<' hello'>; // 'hello'
Vérifier une entrée de type inconnu
function upper(value: unknown): string {
if (typeof value !== "string") throw new TypeError("Expected a string");
return value.toUpperCase();
}
any contourne les vérifications ; unknown nécessite un affinement du type. L’assertion d’affectation définie ! n’initialise pas un champ à l’exécution.