Robert Brax
Robert Brax

Reputation: 7318

How to define function return type of a custom object literal

Here is the object, which is returned from a method in a class:

public dbParameters() // HERE
{
    return {
        "values": this.valuesForDb,
        "keys": this.keysForDb,
        "numbers": this.numberOfValues,
    }
}

Could you please advise how to define the type of the function return, in this case ? Or maybe this is not the proper way to do it and I should use another type instead of the object literal ?

Upvotes: 6

Views: 7105

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

One way could be just a message, that result is a dictinary:

public dbParameters() : { [key: string]: any}
{
    return {
        "values": this.valuesForDb,
        "keys": this.keysForDb,
        "numbers": this.numberOfValues,
    }
}

The other could use some interface

export interface IResult {
    values: any[];
    keys: string[];
    numbers: number[];
}


export class MyClass
{
    public dbParameters() : IResult
    {
        return {
            values: this.valuesForDb,
            keys: this.keysForDb,
            numbers: this.numberOfValues,
        }
    }
}

With interface we have big advantage... it could be reused on many places (declaration, usage...) so that would be the preferred one

And also, we can compose most specific setting of the properties result

export interface IValue {
   name: string;
   value: number;
}
export interface IResult {
    values: IValue[];
    keys: string[];
    numbers: number[];
}

Play with that here

Upvotes: 9

Related Questions