Array.at() 方法缺少打字稿数组类型
Array.at() method missing from typescript array type
有:
const myArray = [0,4,2];
myArray.at(-1);
我在 .at
下得到以下错误
Property 'at' does not exist on type 'number[]'.ts (2339)
这是怎么回事 为什么 Array.at()
不起作用?我是否必须设置某种浏览器列表值来让 TS 知道我希望能够使用此(最近指定的)功能?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
这是我的 tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
看起来即使指定 "lib": "esnext"
也不行 (playground)。
暂时,您可以通过使用您自己的定义文件来扩充数组接口(如所述):¹
declare interface Array<T> {
at(index: number): T | undefined;
}
现在启用它 (playground)。
非常短的订单(编辑:看起来像 非常 短订单,请参阅 ),您应该能够一旦 TypeScript 将其添加到 ESNext
目标(然后在规范于 6 月正式采用后添加到 ES2022
目标;该提案处于第 4 阶段,因此它将在下一个快照中)。
¹ 有一个参数 index?: number
而不是 index: number
,因为规范明确处理了将参数转换为数字导致 NaN
的情况,方法是使用 [=17] =](at
在参数上使用 ToIntegerOrInfinity,它进行替换)。所以根据规范,[10].at()
returns 10
。但希望他们使用更严格的定义。
The Array.prototype.at()
method is part of ES2022
, which didn't quite make it into TypeScript 4.5. It is part of TypeScript 4.6, so once that is officially released (which, according to microsoft/TypeScript#46858 应该是 今天 , 2022-02-22,) 您可以将目标设置为 ES2022
或 ESNext
:
const myArray = [0,4,2]
myArray.at(-1); // okay
有:
const myArray = [0,4,2];
myArray.at(-1);
我在 .at
Property 'at' does not exist on type 'number[]'.ts (2339)
这是怎么回事 为什么 Array.at()
不起作用?我是否必须设置某种浏览器列表值来让 TS 知道我希望能够使用此(最近指定的)功能?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
这是我的 tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
看起来即使指定 "lib": "esnext"
也不行 (playground)。
暂时,您可以通过使用您自己的定义文件来扩充数组接口(如
declare interface Array<T> {
at(index: number): T | undefined;
}
现在启用它 (playground)。
非常短的订单(编辑:看起来像 非常 短订单,请参阅 ESNext
目标(然后在规范于 6 月正式采用后添加到 ES2022
目标;该提案处于第 4 阶段,因此它将在下一个快照中)。
¹ 有一个参数 index?: number
而不是 index: number
,因为规范明确处理了将参数转换为数字导致 NaN
的情况,方法是使用 [=17] =](at
在参数上使用 ToIntegerOrInfinity,它进行替换)。所以根据规范,[10].at()
returns 10
。但希望他们使用更严格的定义。
The Array.prototype.at()
method is part of ES2022
, which didn't quite make it into TypeScript 4.5. It is part of TypeScript 4.6, so once that is officially released (which, according to microsoft/TypeScript#46858 应该是 今天 , 2022-02-22,) 您可以将目标设置为 ES2022
或 ESNext
:
const myArray = [0,4,2]
myArray.at(-1); // okay