打字稿:在界面中将函数作为类型传递

Sam*_*dec 2 typescript reactjs redux

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

示例动作创建者:

export function myFunction(foo: string = "bar") {
    return {
        type: "EXAMPLE_ACTION",
        payload: foo,
    }
}
Run Code Online (Sandbox Code Playgroud)

示例组件:

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)
Run Code Online (Sandbox Code Playgroud)

我认为这可行,但坦率地说这是打字稿错误:

[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,
    }
}
Run Code Online (Sandbox Code Playgroud)

但这似乎过于冗长和冗余,需要导入另一个导出.还有其他方法吗?

Alu*_*dad 6

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

在这种情况下,你会写

import { myFunction } from "actions";

export interface Props {
    myFunc: typeof myFunction;
}
Run Code Online (Sandbox Code Playgroud)

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