Est*_*ask 7 typescript typescript2.0
我正在尝试从包类型中扩展命名空间@typings/fullcalendar.
/// <reference path="./types/fullcalendar" />
import * as fullcalendar from 'fullcalendar';
import { TimeGrid } from 'fullcalendar';
// TimeGrid and fullcalendar.views are used then
Run Code Online (Sandbox Code Playgroud)
原件类型可以在这里看到.
而fullcalendar-custom.d.ts是
import * as FC from 'fullcalendar';
export as namespace FC;
declare class TimeGrid { prepareHits() }
declare let views: any;
Run Code Online (Sandbox Code Playgroud)
这会导致类型错误,因此显然fullcalendar没有正确扩展名称空间:
TS2305:模块'".../node_modules/@ types/fullcalendar/index"'没有导出成员'TimeGrid'.
TS2339:类型'typeof".../node_modules/@ types/fullcalendar/index"'上不存在属性'views'.
该如何以正确的方式完成?
可以reference指令来避免在这里,考虑到types目录中指定typeRoots?
该应用程序与Webpack和awesome-typescript-loader捆绑在一起,因此行为可能与其他编译方法不同.在某些时候,IDE检查(WebStorm)中的类型似乎没问题,但在编译时仍然出现类型错误.
我们可以在非声明中导入名称空间.ts,并将其作为扩展类型再次导出:
// 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;
Run Code Online (Sandbox Code Playgroud)
// use-fc.ts : consumer of extended declaration
import { FC } from "./custom-fc";
console.log(FC.TimeGrid);
console.log(FC.views);
Run Code Online (Sandbox Code Playgroud)
(这与你的场景有所不同,因为我使用的是@types/包和webpack ts-loader,但你应该可以做类似的事情.)
您可以轻松扩展“fullcalendar”或任何其他 TypeScript 命名空间。
示例:创建 fullcalendar-extension.d.ts 文件
/// <reference path="<path-to-typings-dir>/fullcalendar/index.d.ts" />
declare module 'fullcalendar' {
export interface TimeGrid {
customField: string;
customMethod(arg1: number, arg2: boolean): boolean;
prepareHits();
}
namespace customNamespace {
export interface AnotherTimeGrid {
customField1: string;
customField2: boolean;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:确保这个文件被 TypeScript 编译器选中。
使用扩展模块中新定义的类型。
// one way
import { TimeGrid } from 'fullcalendar';
const timeGrid: TimeGrid;
// second way
import * as fc from 'fullcalendar';
const timeGrid: fc.TimeGrid;
const anotherTimeGrid: fc.customNamespace.AnotherTimeGrid;
Run Code Online (Sandbox Code Playgroud)
有关模块和命名空间的更多信息,您可以查看关于模块和命名空间的TypeScript 文档并将它们一起使用。
干杯!
| 归档时间: |
|
| 查看次数: |
4318 次 |
| 最近记录: |