【问题标题】:Typescript: how to select class property by dynamic string打字稿:如何通过动态字符串选择类属性
【发布时间】:2026-01-26 22:45:02
【问题描述】:

我将基于类的 Nuxt 与 Typescript 一起使用,并在尝试通过字符串动态定位属性时出错。

错误是:

Element implicitly has an 'any' type because expression of type '`${string}Products`' can't be used 
to index type 'default'

我还没有找到适合我的解决方案..

代码如下:

export default class extends Vue {

  stateProducts: any[] = [];

  get paperProducts() {
    return this.stateProducts.filter((x) => x.productType === 0);
  }
  get digitalProducts() {
    return this.stateProducts.filter((x) => x.productType === 1);
  }

 getProductStyle(productType: string) { 
    const type:string = productType === 'paper' ? 'digital' : 'paper';
 
    if (!(this[`${type}Products`]).length) {       // <----------------------- error
       
      return 'col-xs-6 col-ms-4 col-sm-3';
    }
    return'col-xs-6 ';
  }

【问题讨论】:

    标签: typescript nuxt.js


    【解决方案1】:

    只需将:string 类型注释移除到type 常量即可。使用 :string 时,您不必要地扩大了最初为 'digital' | 'paper' 的类型,因此让 TS 抱怨。

    【讨论】: