【发布时间】: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