AJP
AJP

Reputation: 28453

duplicate identifier string - TypeScript error in defining object parameter for function interface

Defining the first parameter for a function as an object which must have two keys both containing string values errors with a message: Duplicate identifier 'string'.

interface Func {
    ({value: string; error: string}, {other: number}): number;
}

Upvotes: 3

Views: 3285

Answers (2)

AJP
AJP

Reputation: 28453

You need to name the parameters:

interface Func {
    (firstParameter: {value: string; error: string}, secondParameter: {other: number}): number;
}

Interestingly not naming the second parameter is currently valid TypeScript code which allows you to pass any type of other that you want:

interface Func {
    (firstParameter: {value: string; error: string}, {other: number}): number;
}

var func: Func = function({value: val, error: err}, {other: oth}) {
    return 42;
};

// The type of the second parameter is `{other: any}` which allows you to pass
// a string instead of a number as you might think at a careless first glance:
func({value: 'value', error: 'snap'}, {other: 'bad'});

I am not yet sure what this interface is actually declaring.

Another confusing error message that can arise from not naming the first parameter is: ',' expected. if you have different types for the values, e.g.:

interface Func {
    ({value: string; error: boolean}, {other: number}): number;
}

@MarkDolbyrev's answer above is correct, I wanted to elaborate on it.

Upvotes: 1

Mark Dolbyrev
Mark Dolbyrev

Reputation: 1997

You've forgotten to add names for the parameters. The next code works for me:

interface Func
{
    (param1: {value: string; error: string}, param2: {other: number}): number;
}

Upvotes: 8

Related Questions