如何在Typescript中向对象文字添加函数?

时间:2017-05-18 15:05:33

标签: typescript

我有类似的东西..

let orders = {};
let app: {orders: object} = {orders: orders};

let getNumber = function(orders: object): number {
    //some code here
    return some value
};

app.orders[1] = 'something';
let n = getNumber(app.orders);

以上作品。但我试图通过在我的应用程序中添加该功能来实现此目的。像这样的对象:

let getNumber = function(): number {
    return this.orders[1]; //or something

};

let app: {orders: object, getNumber: object} = {orders: orders, getNumber: getNumber};

let n = app.getNumber();

这是与

相当的JavaScript
let app = {};
app.orders = {};
app.getNumber = function() {
    return this.orders[1]; //or something //anything the point is that i can act on app.orders
}


let n = app.getNumber()

换句话说 - 在TypeScript中我可以向对象文字添加函数吗?

如果答案是否定的 - 那很好 - 我需要了解如何将其写成一个类。但我想知道上述情况是否可能?

由于

更新

let getValue = function(): string {
    return this.orders[1]; //or something
};
let orders: {1: string} = {1: 'abc'};
let app: {orders: object } = {orders: orders};
let val = getValue.call(app);
console.log(val) ; //abc

1 个答案:

答案 0 :(得分:2)

以下是如何定义函数的类型:

type App = {
    orders: object;
    getNumber: () => number;
}

let app: App = { orders: orders, getNumber: getNumber };