简体   繁体   English

使用 TypeScript 时,如何使用定义文件定义数组中使用的类型?

[英]How can I define the types used in an array with a definition file when using TypeScript?

I am using the datatables plugin datatables.net as below:我正在使用数据表插件 datatables.net 如下:

 oTable = $('#dataTable').dataTable({ });

Here is some code that I have这是我拥有的一些代码

$('#detailData')
    .on('click', '.sort-up', function (event) {
        event.preventDefault();
        var column = $(this).closest('th'),
            columnIndex = column.parent().children().index(column.get(0));
        oTable.fnSort([[columnIndex, 'asc']]);
        return false;
    })

This is giving me the following error with Typescript:这给了我以下打字稿错误:

"Incompatible types in array literal expression" “数组文字表达式中的不兼容类型”

Can anyone give me some advice on how I could fix this?谁能给我一些关于如何解决这个问题的建议? It does not seem to like the fact that columnIndex is a number and 'asc' is a string.它似乎不喜欢 columnIndex 是一个数字而 'asc' 是一个字符串的事实。 On Stack Overflow I saw the following:在 Stack Overflow 上,我看到了以下内容:

var f: any[][] = [
    [Foo, [1, 2, 3]],
    [Bar, [7, 8, 9]],
];

I understand doing I need to do something like this but is there a way I can set up the definition of the fnSort function in a .d.ts file?我明白我需要做这样的事情,但有没有办法在 .d.ts 文件中设置 fnSort 函数的定义?

this should do the job这应该可以完成工作

oTable.fnSort([<any[]>[columnIndex, 'asc']]);

arrays should be of uniform type and since you have mixed types [number, string] it throws compilation error.数组应该是统一类型,因为你有混合类型 [number, string] 它会引发编译错误。 casting it to any[] tells compiler that every value in an array is of type 'any' (which is true btw ;) ).将其强制转换为 any[] 告诉编译器数组中的每个值都是“any”类型(顺便说一句,这是真的;))。 compiler will then generate correct js.然后编译器会生成正确的js。 its just a way to fool typescript compiler a bit它只是一种欺骗打字稿编译器的方法

you can do it other way around also - convert columnIndex to string, but if you need it to be number then you have to cast array to any[]你也可以用其他方式来做 - 将 columnIndex 转换为字符串,但如果你需要它是数字,那么你必须将数组转换为 any[]

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

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