【问题标题】:TypeScript type checking JSX childrenTypeScript 类型检查 JSX 子级
【发布时间】:2017-04-30 07:14:08
【问题描述】:

我的 TypeScript 版本是 2.3.2

据此Type checking JSX children

以下代码应该可以工作:

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'),
);

但我得到以下编译错误:

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 '{}'.

我做错了什么?还是我不明白这个问题试图解决什么问题?

【问题讨论】:

  • 是的,你是对的,但这与我得到的错误无关。

标签: typescript react-jsx


【解决方案1】:

这是因为 React 的定义文件没有更新。

定义文件需要包含interface ElementChildrenAttribute { children: {}; },以便 TypeScript 编译器知道“children”属性的名称。

PR更新定义文件:https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16327)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 2021-11-14
    • 2021-12-29
    • 2012-09-29
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多