gpt4 book ai didi

typescript - 在 Typescript 中使用 ECMA6 数组方法?

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:19 24 4
gpt4 key购买 nike

我可以在 Typescript 中使用新的 ECMA6 数组方法,例如 find()includes() 吗?它们似乎有效,尽管编译器说:

error TS2339: Property 'find' does not exist on type 'User[]'.

The documentation暗示它应该在它说的时候工作

TypeScript supports new features in JavaScript, like support for class-based object-oriented programming.

那么为什么它给我一个错误呢?

最佳答案

您需要确保 targettsconfig.json设置为 "ES6" :

"target": "ES6" // under "compilerOptions"

这将使它包含 definition filefind(..)Array<T> 中找到.

示例

// test.ts
var a: number[];

a.find(n => n === 3);

然后编译:

tsc test.ts --target ES6 // ok
tsc test.ts --target ES5 // error: Property 'find' does not exist on type 'number[]'

填充

如果您不想以 ES6 为目标,而是使用 polyfill,那么您可以将其添加到定义文件中以供您的代码使用:

interface Array<T> {
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T;
}

关于typescript - 在 Typescript 中使用 ECMA6 数组方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com