[英]How do I provide default values to optional nested props of type Object in typescript + React?
I'm using Typescript and React.我正在使用 Typescript 和 React。 I typically assign default props while destructuring them like so:
我通常在解构它们时分配默认道具,如下所示:
import * as React from "react"
type ComponentProps = {
a: string;
b?: number;
}
const Component: React.FC<ComponentProps> = ({
a,
b = 2
}) => {
//...
}
But if a prop is an object, or even a nested object, is there a way to assign default values to some properties while keeping some as required?但是如果一个 prop 是一个对象,甚至是一个嵌套的对象,有没有办法为某些属性分配默认值,同时根据需要保留一些属性?
For example:例如:
import * as React from "react"
type ComponentProps = {
a: {
b: number;
c?: string;
};
d?: {
e?: number;
f?: string;
};
g?: {
h?: number;
f: string;
};
}
const Component: React.FC<ComponentProps> = ({
/* I'm not sure what to do here...*/
}) => {
//...
}
I guess I'm actually asking three questions.我想我实际上是在问三个问题。
It's possible , but nested destructuring can be difficult to read.这是可能的,但嵌套解构可能难以阅读。 I'd recommend avoiding the pattern when possible.
我建议尽可能避免这种模式。
While destructuring, can I assign a default value to the optional property of a required object, such as ac ?
在解构时,我可以为所需对象的可选属性(例如 ac )分配默认值吗?
If you had to, for a default value for c
:如果必须,对于
c
的默认值:
const Component: React.FC<ComponentProps> = ({
a: {
b,
c = 'foo',
}
// ...
}) => {
//...
}
While destructuring, if I assign default values to de and df, and when used only de is provided, will df still be retained?
解构时,如果给de和df赋默认值,使用时只提供de,df还会保留吗?
Yes, if you assign a default object to the whole d
:是的,如果您为整个
d
分配一个默认对象:
const Component = ({
d: {
e = 5,
f = 'foo',
} = {},
}: ComponentProps) => {
//...
}
Can you have a required property of an optional object, such as gf
您是否可以拥有可选对象的必需属性,例如 gf
Yes, that's just fine.是的,那很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.