首页 > 解决方案 > 如何将 JavaScript 片段转换为 TypeScript

问题描述

如何将代码从 Javascript 转换为 typescript

const ORIENTATIONS = {
  single: () => 0,
  'right angled': (tag) => {
    return hashWithinRange(tag.text) * 90;
  },
  multiple: (tag) => {
    return hashWithinRange(tag.text) * 15 - 90;
  },
};

我收到了这个错误:

 const ORIENTATIONS: {
    single: () => number;
    'right angled': (tag: any) => number;
    multiple: (tag: any) => number;
}

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ single: () => number; '直角':(标签:任何)=>数字;多个:(标签:任何)=>数字;}'。在“{ single: () => number; 类型上找不到带有“字符串”类型参数的索引签名;'直角':(标签:任何)=>数字;多个:(标签:任何)=>数字;}'.ts(7053)

标签: javascripttypescript

解决方案


您可以创建一个类

export class AppComponent {
  name = "Angular";

  ORIENTATIONS = {
    single: () => 0,
    "right angled": tag => {
      return this.hashWithinRange(tag.text) * 90;
    },
    multiple: tag => {
      return this.hashWithinRange(tag.text) * 15 - 90;
    }
  };

  hashWithinRange(value) {
    return 45;
  }
}

演示https://stackblitz.com/edit/angular-qm5wdc


推荐阅读