首页 > 解决方案 > 在 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>
    );

标签: reactjstypescript

解决方案


const SpeakersMain: React.FunctionComponent<Props> = ...;

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

SpeakersMain: React.FunctionComponent意味着SpeakersMain变量是React.FunctionComponent类型的。虽然<Props>添加了说明,因为在 React类型中React.FunctionComponent被定义为泛型类型。<>语法允许Props作为参数传递。

React.FunctionComponent<Props>type 意味着它是一个以Propstype 作为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 */ };

推荐阅读