我有一個界面讓我們說:
interface SampleInterface {
[key: string]: string;
}
通常我們會定義一個常量為:
const sampleConstant: SampleInterface = {
key: 'value'
}
為什么我做不到
const sampleConstantWithMethod: SampleInterface = {
someMethod(): 'value'
}
function someMethod(): string {
return 'key'
}
是否有一些解決方法,同時仍在使用介面?
uj5u.com熱心網友回復:
聽起來您正在尋找一個計算屬性,它通過將鍵運算式包裝在方括號中來表示,如下所示:
const sampleConstantWithMethod: SampleInterface = {
[someMethod()]: 'value' // okay
}
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/514953.html
標籤:打字稿
