Shalin LK
Shalin LK

Reputation: 190

Trouble in passing interface as an argument

I am new to TypeScript (Version 1.8.10). I have this code;

interface SomeInterface {
    label: string;  
}

function interfaceTester(arg: SomeInterface){
    console.log("This is the interface tester's argument : ", arg.label);
}

//working
interfaceTester({label:"Label value alone"});

But, when I tried this code, with an additional parameter,

interfaceTester({someOneElse: 45, label:"Label value with one extra argument;"});

it is not working; It throws compile error;

Instead when I tried the same(I believe so) this way :

let obj = {someOneElse: 45, label:"Label value with one extra argument;" };

interfaceTester(obj);

is working fine; I could compile and execute it.

Am I doing anything wrong? Can anyone help please?

Upvotes: 0

Views: 43

Answers (2)

Rajeesh Madambat
Rajeesh Madambat

Reputation: 3751

   let obj = {someOneElse: 45, label:"Label value with one extra argument;" };

while building compiler treats the obj as of type any rather specific type of the interface (SomeInterface). This assumes the compiler to treat the variable as dynamic.

To restrict this you should specify the data type.

 let obj: SomeInterface = { someOneElse: 45, label: "Label value with one extra argument;" };

This will give the build error.

Upvotes: 2

Remo H. Jansen
Remo H. Jansen

Reputation: 25019

That is the expected behavior. You can solve it using a casting:

interfaceTester(<SomeInterface>{someOneElse: 45, label:"Label value with one extra argument;"});

You can find documentation about why it works this way here.

Upvotes: 0

Related Questions