从包类型扩展命名空间 [英] Extend a namespace from package typings
问题描述
我在这里尝试从包类型扩展命名空间,@typings/fullcalendar
.
I'm trying here to extend a namespace from package typings, @typings/fullcalendar
.
/// <reference path="./types/fullcalendar" />
import * as fullcalendar from 'fullcalendar';
import { TimeGrid } from 'fullcalendar';
// TimeGrid and fullcalendar.views are used then
原始类型可以在这里看到.
fullcalendar-custom.d.ts 是
And fullcalendar-custom.d.ts is
import * as FC from 'fullcalendar';
export as namespace FC;
declare class TimeGrid { prepareHits() }
declare let views: any;
这会导致类型错误,所以很明显 fullcalendar
命名空间没有正确扩展:
This results in type errors, so it is obvious that fullcalendar
namespace wasn't extended properly:
TS2305:模块.../node_modules/@types/fullcalendar/index"没有导出成员TimeGrid".
TS2305: Module '".../node_modules/@types/fullcalendar/index"' has no exported member 'TimeGrid'.
TS2339:类型typeof".../node_modules/@types/上不存在属性views"完整日历/索引"'.
TS2339: Property 'views' does not exist on type 'typeof ".../node_modules/@types/ fullcalendar/index"'.
应该如何以正确的方式做到这一点?
How should this be done the right way?
考虑到typeRoots
中指定了types
目录,这里可以避免reference
指令吗?
Can reference
directive be avoided here, considering that types
directory is specified in typeRoots
?
该应用程序与 Webpack 和 awesome-typescript-loader 捆绑在一起,因此其行为可能与其他编译方法不同.在某些时候,IDE 检查 (WebStorm) 中的类型似乎没问题,但在编译时仍然出现类型错误.
The application is bundled with Webpack and awesome-typescript-loader, so the behaviour may differ from other compilation methods. At some point types seemed to be ok in IDE inspections (WebStorm) but still got type errors on compilation.
推荐答案
我们可以在非声明的 .ts
中导入命名空间,然后再将其导出为扩展类型:
We can import a namespace in a non-declaration .ts
, and export it again as a extended type:
// custom-fc.ts : enhances declaration of FC namespace
import * as origFC from "fullcalendar";
declare namespace Complimentary {
class TimeGrid {
prepareHits(): void;
}
let views: any;
}
// apply additional types to origFc and export again
export const FC: (typeof Complimentary & typeof origFC) = origFC as any;
// use-fc.ts : consumer of extended declaration
import { FC } from "./custom-fc";
console.log(FC.TimeGrid);
console.log(FC.views);
(这在某种程度上与您的场景有所不同,因为我使用的是 @types/
包和 webpack ts-loader
,但您应该能够做类似的事情.)
(This somehow differs from your scenario, in that I'm using @types/
packages and webpack ts-loader
, but you should be able to do something similar.)
这篇关于从包类型扩展命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!