首页 文章

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

提问于
浏览
2

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

示例动作创建者:

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,
    }
}

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

1 回答

  • 6

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

    在这种情况下,你会写

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

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

相关问题