简体   繁体   English

如何创建 JavaScript 变量以用于 TypeScript generics

[英]How to create JavaScript variables for use with TypeScript generics

I have a TypeScript file:我有一个 TypeScript 文件:

export class Table<T> {
    private readonly records: Record<string, T> = {};
}

export function foo(table: Table<number>) {
    console.log('Foo');
}

And I have a JavaScript file我有一个 JavaScript 文件

import { Table, foo } from './scratch';

let table = new Table();
foo(table);

The table argument in foo(table) is underlined yellow with the warning foo(table)中的table参数带有警告的黄色下划线

Argument type Table  is not assignable to parameter type Table
...
    Type Record  is not assignable to type Record
    Type unknown is not assignable to type number 

How can I make the IDE (WebStorm) not yell at me about this (preferably through code changes and not IDE settings)?我怎样才能让 IDE (WebStorm) 不对我大喊大叫(最好通过代码更改而不是 IDE 设置)?

One way (but not necessarily the optimal way) is to extend the generic class with a typed version before using it in JavaScript:一种方法(但不一定是最佳方法)是在 JavaScript 中使用之前使用类型化版本扩展通用 class:

export class Table<T> {
    private readonly records: Record<string, T> = {};
}

export class NumberTable extends Table<number> {}

It's not fool-proof since it does require modifying the TypeScript source instead of typing the JavaScript source, but it does the trick.这不是万无一失的,因为它确实需要修改 TypeScript 源而不是输入 JavaScript 源,但它确实可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM