0

I need to type handleFoo with MyType['foo'].


type MyType {
  foo: () => void
}

const Comp: React.FunctionComponent<{}> = () => {

  function handleFoo() {}

  return ...
}

I don't want to use Anonymous function like const handleFoo: MyType['foo'] = () => {}

I also tried <MyType['foo']>function handleFoo() {} like recommended here but it's not working in tsx (Operator '>' cannot be applied to types 'string[]')

4
  • 1
    const foo: MyType["foo"] = function () {...}? Otherwise you have to type the parameters and return value separately. Commented Dec 31, 2020 at 11:02
  • I know, but I wanted to know if I could type the function directly Commented Dec 31, 2020 at 11:22
  • 1
    You'd have to use typescriptlang.org/docs/handbook/… and typescriptlang.org/docs/handbook/…, I think. Commented Dec 31, 2020 at 11:23
  • @jonrsharpe you mean like this? function handleFoo(...args: Parameters<MyType["foo"]>): ReturnType<MyType["foo"]> {} lol you're right that would technically work, verbose and funky af tho Commented Dec 31, 2020 at 11:27

1 Answer 1

1

Whatever your reason for avoiding the anonymous function, you can still type a function by assigning it to a variable, even if it isn't anonymous:

const handleFoo: MyType["foo"] = function () {}

Edit: as @jonrsharpe pointed out, there are some utility classes you could use here, but the results, uh, leave something to be desired:

function handleFoo(...args: Parameters<MyType["foo"]>): ReturnType<MyType["foo"]> {}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I didn't want to assign to a variable but looks like it's the only way
@HaJa nope, function declarations can not be typed based on an alias, they must be explicitly typed inline, unlike function expressions.

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.