微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 JavaScript 中使用 @type 声明类方法的类型

如何解决在 JavaScript 中使用 @type 声明类方法的类型

当我使用 @type 在 JavaScript 中使用 d.ts 声明类方法的类型时(请参阅 Type Checking JavaScript Files),如果我使用方法的缩写形式,则参数类型确定不正确入口。如果我使用带有 function 的表单,则一切正常。

这是错误,还是故意实施的?

PS: 为类中定义的方法使用接口也不起作用

通用测试.d.ts

declare module 'MyTest' {

  interface MyTest_FN1 {
    (a: [string,...Array<string>]): string[]
  }

  interface TestFN {
    (name: string,...args: string[]): string[]
  }
}

它不起作用:

/// <reference path="./test.d.ts"/>
// @ts-check

/** test class */
class MyTest {

  /** @type {import('MyTest').MyTest_FN1} */
  fn1(args) {
    return testFn(...args)
  }

}

/** @type {import('MyTest').TestFN} */
function testFn(name,...args) {
  return [name,...args]
}
npx tsc --allowJs --checkJs --noEmit ./test.js
> test.js:9:19 - error TS2556: A spread argument must either have a tuple type or be passed 

enter image description here

如果添加@implements,问题依旧:

  interface MyTestCLS {
   fn1: MyTest_FN1
  }
/** @typedef {import('MyTest').MyTestCLS} IMyTest */
/** @implements {IMyTest} */
class MyTest {

  /** @type {import('MyTest').MyTest_FN1} */
  fn1(args) {
    // args hav a type??
    return testFn(...args)
  }

}

enter image description here

它有效:

/// <reference path="./test.d.ts"/>
// @ts-check

/** test class */
class MyTest {

  /** @type {import('MyTest').MyTest_FN1} */
  fn1 = function test(args) {
    // args have a type??
    return testFn(...args)
  }

}

/** @type {import('MyTest').TestFN} */
function testFn(name,...args]
}

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。