打字稿:重新输入类方法

时间:2019-02-27 09:12:18

标签: typescript class

我在打字稿中重新键入类方法有一些问题。有一个带有默认功能的类isPlaceholdFunc,它还接收字符串和数字类型的参数。问题是:我想在使用isPlaceholdFunc方法的同时击中类型,但是ts会告诉我有未使用的参数。

class Foo {
  isPlaceholdFunc (name: string, age: number) {
    // It's empty by default, user can override it.
    // But ts will tell you that there are unused parameters.
    return null
  }

  callPlaceholdFunc () {
    this.isPlaceholdFunc('123', 456)
  }
}

这是我的一些选择:

  1. 使用@ts-ignore
class Foo {
  // @ts-ignore
  isPlaceholdFunc (name: string, age: number) {
    // It's empty by default, user can override it.
  }

  callPlaceholdFunc () {
    // always receive params as `string`, `number`
    this.isPlaceholdFunc('123', 456)
  }
}
  1. 将类方法转换为attr类
class Foo {
  isPlaceholdFunc: (name: string, age: number) => void = function () {
    // It's empty by default, user can override it.
  }

  callPlaceholdFunc () {
    // always receive params as `string`, `number`
    this.isPlaceholdFunc('123', 456)
  }
}

两个选项都可以,但是它们不够优雅。有什么建议吗?

0 个答案:

没有答案