[label:string]的语法:作为参数接收时的数字类型?

时间:2019-07-08 08:23:09

标签: typescript

以下是IPriceMap的示例:

{
  13123-1231: 2
  2342-343: 1
}

它具有界面:

interface IPriceMap {
    [productId: string]: number;
}

我想将其作为参数接收,但是无法引用IPriceMap。我该如何实现?请参阅下面的问号。

public async updatePrices(quotationId: Id, priceMap: ?) {
    ...
}

1 个答案:

答案 0 :(得分:2)

目前尚不清楚为什么不能使用IPriceMap

但是您可以使用内联类型:

public async updatePrices(quotationId: Id, priceMap: {[productId: string]: number}) {
    // ...
}

或者只是为其声明类型:

// Stand-in for IPriceMap
declare type MyPriceMap = {
  [productId: string]: number
}

class X {
    public async updatePrices(quotationId: Id, priceMap: MyPriceMap) {
        // ...
    }
}

不过,这实际上不是必需的,而且这是不好的做法(因为更改IPriceMap意味着上述类型将变为错误)。

或者当然是any

public async updatePrices(quotationId: Id, priceMap: any) {
    // ...
}

...至少具有以下优势:如果IPriceMap发生了变化,实际上并没有错,只是...含糊不清。