this parameters

function fn( this: void ) { // Property 'alert' does not exist on type 'void'.(2339) this.alert(); } function fn2( this: Window ) { this.alert(); } interface Person { age: number; } function fn3( this: Person ) { console.log( this.age ); } // The 'this' context of type 'void' is not assignable to method's 'this' of type 'Person'.(2684) fn3(); fn3.call( new class implements Person { age = 100; } )
interface UIElement { addClickListener( onclick: ( this: void, e: Event ) => void ): void; }
this: void means that addClickListener expects onclick to be a function that does not require a this type.
function add( this: { x : number }, y: number ): number { return this.x + 1; } // The 'this' context of type 'void' is not assignable to method's 'this' of type '{ x: number; }'.(2684) add( 10 ); add.call( { x : 10 }, 10 ); add.bind( { x : 10 } )( 10 ); const obj = { x : 10, add }; obj.add( 10 );

Overloads

In order for the compiler to pick the correct type check, it follows a similar process to the underlying JavaScript. It looks at the overload list and, proceeding with the first overload, attempts to call the function with the provided parameters. If it finds a match, it picks this overload as the correct overload. For this reason, it's customary to order overloads from most specific to least specific.
function create( name: string ): boolean; function create( name: boolean ): string; function create( name: string | boolean ): boolean | string { if( typeof name === 'string' ) { return 'string'; } return true; } ParameterType<create>; // Type 'boolean' is not assignable to type 'string'.(2322) const a: string = create( 'A' ); // Type 'string' is not assignable to type 'boolean'.(2322) const b: boolean = create( true );
Note that the function create( name: string | boolean ): boolean | string piece is not part of the overload list, so it only has two overloads.

Literal Types

function create( name: 'A' ): boolean; function create( name: 'B' ): string; function create( name: string ): boolean | string { if( name === 'A' ) { return 'A'; } return true; } // Type 'boolean' is not assignable to type 'string'.(2322) const a: string = create( 'A' ); // Type 'string' is not assignable to type 'boolean'.(2322) const b: boolean = create( 'B' );
// This overload signature is not compatible with its implementation signature.(2394) function create( name: 'A' ): boolean; function create( name: 'B' ): string; function create( name: string ): number { return 1; }
 
badge