Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type checking JSX children

My TypeScript Version is 2.3.2

According to this Type checking JSX children

The following code should work:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

interface TestProps {
    children: string | JSX.Element;
}

const Foo = (props: TestProps) => <div>{props.children}</div>;

// Error on Foo
ReactDOM.render(
    <Foo>
        <div>Test</div>
    </Foo>,
    document.getElementById('content'),
);

But i get the following compilation error:

TestTsxChildren> tsc --version
Version 2.3.2
TestTsxChildren> tsc
main.tsx(11,5): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & TestProps'.
  Type '{}' is not assignable to type 'TestProps'.
    Property 'children' is missing in type '{}'.

What did i do wrong? Or did i not understand what the issue was trying to fix?

like image 784
VSDekar Avatar asked Apr 30 '17 07:04

VSDekar


1 Answers

This is because the definition file for React is not updated.

The definition file needs to include interface ElementChildrenAttribute { children: {}; } so that TypeScript compiler known the name of the "children" property.

PR to update the definition file: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16327)

like image 106
Yui T. Avatar answered Oct 23 '22 18:10

Yui T.