[英]How to type named, optional parameter that accepts an object with optional fields that have defaults in TypeScript-React?
I want something like the style
prop in the default HTML components:我想要默认 HTML 组件中的
style
道具之类的东西:
<div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}>
style
itself is an optional prop, and the fields inside the object passed to style
are optional too (and I assume they have defaults). style
本身是一个可选的道具,传递给style
的 object 中的字段也是可选的(我假设它们有默认值)。 I wish I could just look at the source code to figure out how it's done, but it just looks like complete gibberish to me.我希望我可以只看源代码来弄清楚它是如何完成的,但对我来说它看起来完全是胡言乱语。
function a({
param1 = 'default param1',
options = { option1: 'default option1', option2: 'default option2' },
}: {
param1?: string;
options?: { option1?: string; option2?: string };
}) {
console.log(param1);
console.log(options);
}
a({});
a({ param1: 'my param1' });
a({ param1: 'my param1', options: { option1: 'my option1' } });
[LOG]: "default param1"
[LOG]: {
"option1": "default option1",
"option2": "default option2"
}
[LOG]: "my param1"
[LOG]: {
"option1": "default option1",
"option2": "default option2"
}
[LOG]: "my param1"
[LOG]: {
"option1": "my option1"
}
This almost works but the default for options
is overridden completely when I only pass in option1
.这几乎可以工作,但是当我只传入
option1
时, options
的默认值被完全覆盖。 How do I set defaults for each field in options
individually?如何分别为
options
中的每个字段设置默认值?
You can do something along these lines if you only care about individual options:如果您只关心个别选项,则可以按照以下方式做一些事情:
function a({
param1 = 'default param1',
options,
}: {
param1?: string;
options?: { option1?: string; option2?: string };
}) {
const {option1 = 'default option1', option2 = 'default option2'} = options ?? {}
console.log(param1);
console.log({option1, option2});
}
Alternatively, you could use Object.assign
to build your options objects, eg或者,您可以使用
Object.assign
来构建您的选项对象,例如
const defaultOptions = {
option1: 'default option1',
option2: 'default option2'
}
function a({
param1 = 'default param1',
options,
}: {
param1?: string;
options?: { option1?: string; option2?: string };
}) {
const effectiveOptions = Object.assign({}, defaultOptions, options)
console.log(param1);
console.log(effectiveOptions);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.