Interface function definitions

Interfaces, like classes, follow the same rules when dealing with functions. To update our IComplexType interface definition to match the ComplexType class definition, we need to write a function definition for each of the new functions, as follows:

interface IComplexType { 
    id: number; 
    name: string; 
    print(): string; 
    usingTheAnyKeyword(arg1: any): any; 
    usingOptionalParameters(optionalArg1?: number) : void; 
    usingDefaultParameters(defaultArg1?: number) : void; 
    usingRestSyntax(...argArray: number []) : void; 
    usingFunctionCallbacks(callback: (id: number) => string); 
} 

This interface definition includes the id and name properties and a print function. We then have a function signature for the usingTheAnyKeyword function. It looks surprisingly like our actual class function, but does not have a function body. The usingOptionalParameters function definition shows how to use an optional parameter within an interface.

The interface definition for the usingDefaultParameters function, however, is slightly different to our class definition. Remember that an interface defines the shape of our class or object, and therefore cannot contain variables or values. We have therefore defined the defaultArg1 parameter as optional, and left the assignment of the default value up to the class implementation itself. The definition of the usingRestSyntax function contains the rest parameter syntax, and the definition of the usingFunctionCallbacks function shows how to define a callback function signature. They are pretty much identical to the class function signatures.

The only thing missing from this interface is the signature for the constructor function. Interfaces cannot include signatures for a constructor function.

Let's take a look at why this causes errors in our compilation step. Suppose we were to include a definition for the constructor function in the IComplexType interface:

interface IComplexType { 
    constructor(arg1: any, arg2: any); 
} 

The TypeScript compiler would then generate the following error:

error TS2420: Class 'ComplexType' incorrectly implements interface 'IComplexType'.
Types of property 'constructor' are incompatible.  

This error shows us that, when we use a constructor function, the return type of the constructor is implicitly typed by the TypeScript compiler. Therefore, the return type of the IComplexType constructor would be IComplexType, and the return type of the ComplexType constructor would be ComplexType. Even though the ComplexType function implements the IComplexType interface, they are actually two different types. Therefore, the constructor signatures will always be incompatible, and are not allowed in interface definitions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.86.155