4

I am trying to figure out how to get type out of existing Typescript function and use it to define interface. I am working on React project and I want to pass action creator (function) to Props interface and then into React Component as Component<Props, State>.

Example action creator:

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

Example component:

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)

I was thinking this could work, but frankly it's a typescript error:

[ts] Cannot find name 'myFunction'

I was wondering if i have to define a separate type to pass it to my component, something like this:

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

but that seems too verbose and redundant and would need to import another export. Is there any other way around this?

1 Answer 1

6

You can use the typeof keyword in type position to obtain the type of a named value.

In this case you would write

import { myFunction } from "actions";

export interface Props {
    myFunc: typeof myFunction;
}

The reason you currently receive an error is that TypeScript has two distinct declaration spaces, one for values and one for types. function defines a value but not a type.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah thanks, works great. Somehow I didn't even think about that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.