在TypeScript中,何时使用<>和何时使用:

皮特

我不知道何时应使用<>以及何时应使用:为属性分配类型。我下面的代码是正确的,但是我不确定为什么要声明React.FunctionComponent<Props>而不是React.FunctionComonent : Props

    interface Props {
        speakers : Speaker[]
    }

    const SpeakersMain : React.FunctionComponent<Props> = (props : Props) => (
        <div>
            <SpeakersHeader/>
            <SpeakerList speakers={props.speakers} />
        </div>
    );
那将是烧瓶
const SpeakersMain: React.FunctionComponent<Props> = ...;

应该使用,因为使用:afterReact.FunctionComponent将是不正确的语法。

SpeakersMain: React.FunctionComponent表示SpeakersMain变量是React.FunctionComponent类型。虽然<Props>添加了澄清,React.FunctionComponent因为在React类型被定义为泛型类型<>语法允许Props作为参数传递

React.FunctionComponent<Props>type表示它是一个将Props类型作为其props参数的函数。

它的工作方式是:

type Foo<T = {}> = (props: T) => void;
type Bar = { bar: number };

var foo1: Foo = (props) => { /* props is supposed to be empty object by default */ };
var foo2: Foo<Bar> = (props) => { /* props is supposed to be Bar */ };

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章