[英]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 是
import * as FC from 'fullcalendar';
export as namespace FC;
declare class TimeGrid { prepareHits() }
declare let views: any;
这会导致类型错误,因此很明显fullcalendar
命名空间没有正确扩展:
TS2305:模块 '".../node_modules/@types/fullcalendar/index"' 没有导出成员 'TimeGrid'。
TS2339:属性“views”在类型“typeof“.../node_modules/@types/fullcalendar/index”上不存在。
这应该如何以正确的方式完成?
考虑到types
目录是在typeRoots
指定的,这里可以避免reference
指令吗?
该应用程序与 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;
// use-fc.ts : consumer of extended declaration
import { FC } from "./custom-fc";
console.log(FC.TimeGrid);
console.log(FC.views);
(这在某种程度上与您的场景有所不同,因为我使用的是@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;
}
}
}
注意:确保这个文件被 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;
有关模块和命名空间的更多信息,您可以查看关于模块和命名空间的TypeScript 文档并将它们一起使用。
干杯!
使用最新的 TypeScript v4,当我在将外部文件和库与Svelte结合时遇到问题时,我这样做了:
// root/my-declarations.d.ts
import { SomeNameSpace as SomeNameSpaceOriginal} from '../../any-relative-path/to/ts-file';
import {SvelteComponentDev} from 'svelte/internal';
declare namespace SomeNameSpaceExtended {
function setValue(value:any):any
let UI:SvelteComponentDev
let abc:string
}
declare global {
//this will add new items to top-level (root)
//note: in my case, only importing "as SomeNameSpaceOriginal" gave me correct typing later using our new extended global SomeNameSpace
let SomeNameSpace: typeof SomeNameSpaceOriginal & typeof SomeNameSpaceExtended;
//this will add new items to window:
interface Window {
elementInside:'window.elementInside'
}
}
Upvoted Answer 结合https://stackoverflow.com/a/63973683 可以让您最了解如何扩展事物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.