【发布时间】:2020-12-07 21:00:51
【问题描述】:
问题: 我发现@types/lodash 方法首先没有涵盖输入的案例类型是两个(多个)类型化数组的联合: // 在我的文件中,我有 从'lodash'导入*作为_;
interface First {
name: string;
}
interface Second {
age: number;
}
function performSomeLogic(): First[] | Second[] {
if (Math.random() > 0.5) return [{name: 'Alice'}, {name: 'Bob'}];
return [{age: 42}, {age: 33}];
}
// we got some array First or Second of type. ok
const returnedData = performSomeLogic(); // we got some array First or Second of type. ok
// we expect value is First or Second of type. NOT ok.
// *******************
// TS ERROR
// TS2345: Argument of type 'First[] | Second[]' is not assignable to
// parameter of type 'ArrayLike<First>'.
// *******************
const firstValueOfData = _.first(returnedData);
// further steps could be ..
const proceedWithValueOfData = (value: First | Second) => Object.keys(value);
proceedWithValueOfData(firstValueOfData);
想法: 我想出了 _.first() 的正确接口。我尝试将其放入 typings.d.ts 添加参考它以供捆绑器使用:
// typings.d.ts
type DeriveArrTypes<T> = T extends (infer R)[] ? R : T;
// So DeriveArrTypes<First[] | Second[]> returns First|Second union
declare module 'lodash' {
// LoDashStatic IS THE INTERFACE LODASH HAS HAD. FIRST IS DECLARED IN IT. I WANT TO ADD ITS EXTENDED DECLARATION
interface LoDashStatic {
first<T extends []>(value: T): DeriveArrTypes<T> | undefined;
}
}
成功 - 否: 但这不起作用。 Typescript 停止显示任何错误(包括其他不同的错误)。我使用 WebStorm 作为 IDE,它会继续突出显示。
环境: 它是一个前端项目,由 Typescript 用于转译和 Webpack 用于捆绑(由于其长期持续的活跃性:))。 来自 webpack.config.js:
// the rule for ts
{
test: /\.ts$/,
use: [{
loader: 'ts-loader',
options: {
// disable type checker - we will use it in fork plugin
transpileOnly: true
}
}],
},
// plugins section
plugins: [
// bla-bla plugins
...
new ForkTsCheckerWebpackPlugin({
tsconfig: __dirname + '/tsconfig.json'
})
]
来自 tsconfig.json:
"compilerOptions": {
// bla-bla options
...
"typeRoots": [
"node_modules/@types"
],
}
// I ADDED THIS
"include": [
"app/typings/**/*"
],
当我创建 app/typings 目录并将 typings.d.ts 放入其中时。
【问题讨论】:
-
declare module "lodash"是你想要的。这是您要扩充的模块说明符,因此是一个字符串 -
@AluanHaddad 非常感谢。我听从你的建议,因为它是正确的符号,我错过了。但是,它不能解决问题。我会说我看不到任何影响。
-
这是一个先决条件。我不是说这就是你所要做的,我只是看了你的问题,但这是必要的。
-
@AluanHaddad 谢谢。我很感激。我在上面的问题中更新了我的语法。
-
请注意,您需要在模块上下文中才能使其工作,否则它不是增强。只需将
export {}添加到文件顶部,以确保即使您删除导入,它仍然是一个模块
标签: typescript lodash typescript-typings definitelytyped