Ric*_*nia 6 typescript reactjs
假设我有一个这样的课程:
class PeopleByTag extends React.Component<RouteComponentProps<{ tag: string }>
Run Code Online (Sandbox Code Playgroud)
我需要在我的构造函数中做一些事情,在这个例子中获取数据,但要做到这一点,我需要声明一个 props 参数,但如果我不指定类型,它将变成任何类型:
constructor(props) {
super(props); // props is any
this.loadData();
}
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我重新声明类型,代码会变得非常难看:
constructor(props: Readonly<{
children?: React.ReactNode;
}> & Readonly<RouteComponentProps<{
tag: string;
}, StaticContext, any>>) {
super(props);
this.loadData();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法从类扩展中自动推断 props 类型,同时还可以编写构造函数?
我也不想使用已弃用的生命周期挂钩(即 ComponentWillMount)。
通常 constructor 它本身不应该变得“非常难看”,因为类型可以单独定义,type或者interface以防参数类型很冗长。
props无法推断构造函数参数,因为React.Component<RouteComponentProps<{ tag: string }>>泛型参数引用的是父类,React.Component而不是当前类。
正如在类型定义中可以看到的,这推断了父构造函数的正确类型,即super。
所以这
constructor(props) {
super(props);
}
Run Code Online (Sandbox Code Playgroud)
已验证。this.props仍然正确输入。
如果noImplicitAny使用编译器选项,则为:
constructor(props: any) {
super(props);
}
Run Code Online (Sandbox Code Playgroud)
在构造函数中使用propstyped asany可能会导致类型错误:
constructor(props: any) {
super(props);
props.tag; // ok
props.nonexistentProp; // ok
}
Run Code Online (Sandbox Code Playgroud)
whilethis.props是类型安全的。
可以将类键入为泛型,以在构造函数中维护正确的 props 类型,但这可能被认为是矫枉过正:
export class PeopleByTag<P extends { tag: string }> extends React.Component<P> {
constructor(props: Readonly<P>) {
super(props); // props is any
props.tag; // ok
props.nonexistentProp; // not ok
props.children; // not ok, but we rarely ever need children in constructor
}
}
Run Code Online (Sandbox Code Playgroud)
props通过为其提供不兼容的类型来防止在构造函数中使用它可能是有益的:
constructor(props: never) {
super(props);
props.tag; // not ok
}
Run Code Online (Sandbox Code Playgroud)
如果props参数被传递给super, ,this.props和props在 JavaScript 中可以互换。它们在 TypeScript 中不可互换。this.props可以在构造函数中访问正确类型的 props。
| 归档时间: |
|
| 查看次数: |
2660 次 |
| 最近记录: |