【问题标题】:What does the 'new' keyword before the parameter list mean in a typscript arrow function? [duplicate]在打字稿箭头函数中,参数列表之前的“新”关键字是什么意思? [复制]
【发布时间】:2023-03-04 12:36:01
【问题描述】:

我对 TypeScript 甚至 JavaScript 还是很陌生。我一直在尝试围绕 Microsoft 的一个示例来了解如何将 AzureAD 身份验证集成到 React 应用程序中。该示例使用 HOC 为组件提供身份验证。 HOC 的声明如下所示:

function withAuthProvider<T extends React.Component<AuthComponentProps>>(
    WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}

大部分内容或多或少都清楚。让我困惑的是WrappedComponent 的类型。具体来说,我不明白 new 关键字在这种情况下的作用。

谁能帮帮我?

【问题讨论】:

    标签: javascript reactjs typescript higher-order-components


    【解决方案1】:

    这是一个构造函数类型。这意味着当你用new调用它时,你可以给它一个props参数和一个可选的context参数,它会构造一个T类型的实例。

    这是一个例子:

    class Foo {
        private value: number;
        constructor(x: number, y: number = 1) {
            this.value = x + y;
        }
    }
    
    const foo: new (arg1: number, arg2?: number) => Foo = Foo;
    // can be invoked like this (with new)
    const x1: Foo = new foo(1);
    const x2: Foo = new foo(1, 2);
    // cannot be invoked without new
    // these lines will error at both compile- and run-time
    const y1: Foo = foo(1);
    const y2: Foo = foo(1, 2);
    

    【讨论】:

    • 感谢您的回答。你介意详细说明一下这个主题吗? '用新调用'是什么意思?在示例中调用它的方式是:class App extends React.Component {...} ... export default withAuthentication(App)。签名是否意味着您传递的类必须具有接受props: AuthComponentProps 和可选context 的构造?还有其他方法可以调用该函数吗?
    • 啊,我明白了,您的意思是作为参数传递的内容将被new 调用。我以为我可以像const comp = new withAuthentication(props) 那样做某事。谢谢!
    猜你喜欢
    • 2015-05-15
    • 2018-01-23
    • 2016-02-18
    • 2017-05-10
    • 2020-05-26
    相关资源
    最近更新 更多