1

So I have a React project bootstrapped with create-react-app. I'm converting it to Typescript gradually and have, for example, something like:

App.tsx

import React from 'react';
import { TestThing } from './components/TestThing'

function stuff(a: any): void {
  console.log('stuff', a);
}

function App() {
  return (
    <div className="App">
      <TestThing foo="foo" bar={stuff}/>
    </div>
  );
}

export default App;

and a legacy file TestThing.js

import React from 'react';

const DEFAULT_THING = () => {
  console.log('whatever');
};

export const TestThing = ({ foo, bar = DEFAULT_THING }) => 
    <div onClick={bar}>foo = {foo}</div>;

This gives the error:

Type '(a: any) => void' is not assignable to type '() => void'.  TS2322

in App.tsx as I presume Typescript is inferring bar can take no arguments because of it's default assignment in the legacy JS code.

How can I tell TS this is valid without having to touch that legacy JS file?

Thanks!

1
  • DEFAULT_THING should have the same signature as stuff. Either remove a: any from stuff or add it to DEFAULT_THING list of arguments. Commented Mar 31, 2020 at 23:15

1 Answer 1

2

Typescript is correct here. If a function is sometimes called without arguments, you really should mark it as such:

function stuff(a?: any): void {
  console.log('stuff', a);
}

Either that, or turn type checking off for that function.

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

1 Comment

Ah you're right! It was the ? that I hadn't thought about adding. ...you have no idea how long I've been staring at this haha. Thanks so much :-)

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.