【问题标题】:Typescript: passing function as type in interface打字稿:将函数作为接口中的类型传递
【发布时间】:2017-04-24 11:32:21
【问题描述】:

我试图弄清楚如何从现有的 Typescript 函数中获取类型并使用它来定义接口。我正在处理 React 项目,我想将 action creator(函数)传递给 Props 接口,然后作为 Component<Props, State> 传递给 React 组件。

示例动作创建者:

export function myFunction(foo: string = "bar") {
    return {
        type: "EXAMPLE_ACTION",
        payload: foo,
    }
}

示例组件:

import React, { Component } from 'react'
import { connect } from "react-redux"
import { myFunction } from "actions"

export interface Props {
    // This is what I'm trying to and and it ends up in ts error
    myFunc: myFunction
}

class SomeComponent extends Component<Props, {}> {
    render() {
        return (
            <div>
                Example:
                <button onClick={this.props.myFunc("baz")}>Click to dispatch</button>
            </div>
        )
    }
}

export default connect(null, {
    myFunction
})(SomeComponent)

我认为这可以工作,但坦率地说,这是一个打字错误:

[ts] Cannot find name 'myFunction'

我想知道是否必须定义一个单独的 type 才能将其传递给我的组件,如下所示:

export type myFuncType = (foo: string) => { type: string, payload: string }
export const myFunction: myFuncType = (foo: string) => {
    return {
        type: "EXAMPLE_ACTION",
        payload: foo,
    }
}

但这似乎过于冗长和多余,需要导入另一个导出。有没有其他办法解决这个问题?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    您可以在类型位置使用typeof关键字来获取命名值的类型。

    在这种情况下,你会写

    import { myFunction } from "actions";
    
    export interface Props {
        myFunc: typeof myFunction;
    }
    

    您当前收到错误的原因是 TypeScript 有两个不同的声明空间,一个用于值,一个用于类型。 function 定义了一个值而不是一个类型。

    【讨论】:

    • 啊,谢谢,效果很好。不知怎的,我什至没有想到这一点
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2019-02-10
    • 2020-06-22
    • 2017-09-16
    • 2021-06-17
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多