如何定义自定义对象文字的函数返回类型

时间:2016-05-20 09:21:32

标签: typescript

这是对象,它从类中的方法返回:

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

在这种情况下,您能否建议如何定义函数返回的类型?或者这可能不是正确的方法,我应该使用另一种类型而不是对象文字?

1 个答案:

答案 0 :(得分:7)

一种方式可能只是一条消息,结果是一个dictinary:

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

另一个可以使用一些界面

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,
        }
    }
}

使用interface我们有很大的优势......它可以在许多地方重复使用(声明,使用......)以便这是首选的

而且,我们可以组成属性结果的最具体设置

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

使用that here

进行游戏
相关问题