gpt4 book ai didi

javascript - 作为函数且具有 namespace 的模块的 typescript 定义?

转载 作者:行者123 更新时间:2023-11-30 15:58:45 26 4
gpt4 key购买 nike

我正在尝试为 react-grid-layout 制作一个 *.d.ts 文件。作为其index.js文件显示它导出一个函数 - React.Component 的子类 ReactGridLayout:

// react-grid-layout/index.js
module.exports = require('./build/ReactGridLayout').default;
module.exports.utils = require('./build/utils');
// ...

要求:

var ReactGridLayout = require('react-grid-layout');
console.log(ReactGridLayout);
// --> function ReactGridLayout(props , context) { ...

它还会导出一些其他的东西,分成命名空间:

for (var f in ReactGridLayout) {
if (ReactGridLayout.hasOwnProperty(f)) {
console.log(f);
}
}
// --> utils
// ...

因此它执行单个导出多个导出。

我尝试了 Single Complex Object in Modules Typescript 网站和 this declaration file on GitHub 中描述的方法但收效甚微。

更新

暂时忽略其他内容,我对 ReactGridLayout 的定义如下所示:

// react-grid-layout.d.ts
declare module 'react-grid-layout' {

import * as React from 'react';

export default class ReactGridLayout<P,S> extends React.Component<P,S> {

containerHeight():void;

onWidthChange(width:number):void;

/* more methods here ... */

}

哪个编译。但是它生成的 Javascript 如下:

var react_grid_layout_1 = require('react-grid-layout');

React.createElement(react_grid_layout_1.default, null, ...

什么时候应该:

React.createElement(react_grid_layout_1, null, ...    

最佳答案

因为 react-grid-layout 正在“直接”导出 ReactGridLayout 类而不是 default 你不能做 export default(您已经看到发生了什么)。我认为您必须解决 export = 语法,但这似乎限制您只能导出一件事。解决这个问题的一种方法是利用 TypeScript 的声明合并。导出同名的类和命名空间。这或多或少是 react-grid-layout 正在做的事情。

ma​​in.tsx

import * as React from 'react'
import * as ReactGridLayout from 'react-grid-layout'

var grid = new ReactGridLayout(null, null);
var responsiveGrid = new ReactGridLayout.ResponsiveReactGridLayout(null, null);

<ReactGridLayout></ReactGridLayout>
//<ReactGridLayout.ResponsiveReactGridLayout></ReactGridLayout.ResponsiveReactGridLayout>

ma​​in.js(转译)

"use strict";
var React = require('react');
var ReactGridLayout = require('react-grid-layout');
var grid = new ReactGridLayout(null, null);
var responsiveGrid = new ReactGridLayout.ResponsiveReactGridLayout(null, null);
React.createElement(ReactGridLayout, null);
//<ReactGridLayout.ResponsiveReactGridLayout></ReactGridLayout.ResponsiveReactGridLayout>

types.d.ts

declare module 'react-grid-layout' {

import * as React from 'react';

class ReactGridLayout extends React.Component<ReactGridLayout.Props, ReactGridLayout.State> {
// members
}

namespace ReactGridLayout {
export interface State {
activeDrag?: any; // declare LayoutItem, etc..
// etc...
}

export interface Props {
className?: string
// etc...
}

export class ResponsiveReactGridLayout extends React.Component<any, any>
{
// etc
}
}

export = ReactGridLayout;
}

顺便说一句:您可能会发现查看 react-grid-layout 的 ES6 代码会更容易。

关于javascript - 作为函数且具有 namespace 的模块的 typescript 定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38077124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com