6

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 ?

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

Superb answer thanks, I will go with the interface solution. Do you suggest putting interfaces into a single file for entire project, or on per sub apps of the project ?
Yes, exactly.. Interfaces should be extracted (not only one file, but could be even more - per logical structure) ... so, we do have few of them for example - and we try to keep them grouped by modules, types...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.