Tutorial by Examples

Declaring a generic interface interface IResult<T> { wasSuccessfull: boolean; error: T; } var result: IResult<string> = .... var error: string = result.error; Generic interface with multiple type parameters interface IRunnable<T, U> { run(input: T): U; } ...
class Result<T> { constructor(public wasSuccessful: boolean, public error: T) { } public clone(): Result<T> { ... } } let r1 = new Result(false, 'error: 42'); // Compiler infers T to string let r2 = new Result(false, 42); // Compiler infers T...
Simple constraint: interface IRunnable { run(): void; } interface IRunner<T extends IRunnable> { runSafe(runnable: T): void; } More complex constraint: interface IRunnble<U> { run(): U; } interface IRunner<T extends IRunnable<U>, U> { runSafe...
In interfaces: interface IRunner { runSafe<T extends IRunnable>(runnable: T): void; } In classes: class Runner implements IRunner { public runSafe<T extends IRunnable>(runnable: T): void { try { runnable.run(); } catch(e) { } ...
Create generic class instance: var stringRunnable = new Runnable<string>(); Run generic function: function runSafe<T extends Runnable<U>, U>(runnable: T); // Specify the generic types: runSafe<Runnable<string>, string>(stringRunnable); // Let typescript figu...
With TypeScript 1.8 it becomes possible for a type parameter constraint to reference type parameters from the same type parameter list. Previously this was an error. function assign<T extends U, U>(target: T, source: U): T { for (let id in source) { target[id] = source[id]; ...

Page 1 of 1