TypeScript jsdoc对象索引签名语法不会示例化类型变量,

v2g6jxz6  于 9个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(90)

代码

  1. /** @template T */
  2. class C {
  3. /** @param {T} t */
  4. constructor(t) {
  5. /** @type {Object<string, T> } -- does not instantiate T */
  6. this.ot = { p: t }
  7. /** @type {{ [s: string]: T }} -- instantiates T */
  8. this.st = { p: t }
  9. }
  10. }
  11. var c = new C(1)
  12. c.ot.p // should have type number, has type T
  13. c.st.p // has type number

预期行为:

c.ot.p : number

实际行为:

c.ot.p : T
Object<string, T> 的语法类似于类型别名,但它并没有像类型别名那样进行示例化,这可能是问题所在。

kd3sttzy

kd3sttzy1#

哎呀,变量逃逸了它们的范围???我有点惊讶它没有产生某种类型的内部编译器错误。
有一个Playground测试用例:

  1. // @checkJs
  2. // @filename: input.js
  3. /** @template T */
  4. class C {
  5. /** @param {T} t */
  6. constructor(t) {
  7. /** @type {Object<string, T> } -- does not instantiate T */
  8. this.ot = { p: t }
  9. /** @type {{ [s: string]: T }} -- instantiates T */
  10. this.st = { p: t }
  11. }
  12. }
  13. var c = new C(1)
  14. /** @type {number} */
  15. var cotp = c.ot.p // fails: Type 'T' is not assignable to type 'number'.(2322)
  16. /** @type {number} */
  17. var cstp = c.st.p

编译器选项

  1. {
  2. "compilerOptions": {
  3. "strict": true,
  4. "noImplicitAny": true,
  5. "strictFunctionTypes": true,
  6. "strictPropertyInitialization": true,
  7. "strictBindCallApply": true,
  8. "noImplicitThis": true,
  9. "noImplicitReturns": true,
  10. "alwaysStrict": true,
  11. "esModuleInterop": true,
  12. "checkJs": true,
  13. "allowJs": true,
  14. "declaration": true,
  15. "experimentalDecorators": true,
  16. "emitDecoratorMetadata": true,
  17. "target": "ES2017",
  18. "jsx": "react",
  19. "module": "ESNext",
  20. "moduleResolution": "node"
  21. }
  22. }

**Playground链接:**提供

展开查看全部

相关问题