typescript - 为我的项目扩展 lodash 类型(@types/lodash),使用“first”方法的接口
问题描述
问题: 我发现@types/lodash 方法首先没有涵盖输入的案例类型是两个(多个)类型化数组的联合://在我的文件中,我有 import * as _ from '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,它继续突出显示。
ENV: 它是一个前端项目,由 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放入其中时。
解决方案
If you want to add interface to a npm module you can use declare module
keyword
import lodash from "lodash";
declare module "lodash " {
interface First {
name: string;
}
interface Second {
age: number;
}
}
推荐阅读
- javascript - Nodejs FS异步等待S3上传multer
- android - Jetpack Compose 中的 TextClock 等价物是什么?
- python - Mongo 获取一组键,包括嵌套的,以及相关的最近看到的日期
- automation - 如何在 Tosca 工具中对空值进行逐行比较
- list - Flutter:列表已弃用?
- vue.js - PrimeVue:表格列对齐不一致
- kotlin - 当函数成功执行完成时如何让 Kotlin “监听”
- ssrs-2012 - SSRS 报告 - 在报告中将 css/html/xml 格式字段显示为字符串或简单文本
- c# - 无法加载对象列表(
- ) 到 firebase 实时数据库
- python - 调整 QSplitter 的大小不尊重 QSizePolicy 或 setStretchFactor?