Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define function return type of a custom object literal

Tags:

typescript

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 ?

like image 341
Robert Brax Avatar asked Mar 12 '23 06:03

Robert Brax


1 Answers

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

like image 193
Radim Köhler Avatar answered Mar 15 '23 10:03

Radim Köhler