Default values in props with Merge Giving me a weird interface

In the situation where I want to possibly pass in prop, say arrOfStrings:
tsx
interface ComponentProps {
arrOfStrings?: string[]
}

export default function Component(props: ComponentProps) {
const merged = mergeProps(
{
arrOfStrings: [],
},
props
);
// ... etc
}
tsx
interface ComponentProps {
arrOfStrings?: string[]
}

export default function Component(props: ComponentProps) {
const merged = mergeProps(
{
arrOfStrings: [],
},
props
);
// ... etc
}
I'm getting a resulting type for merged as :
ts
const merged: {
arrOfStrings: (string[] | never[]) & (string[] | never[] | undefined);
}
ts
const merged: {
arrOfStrings: (string[] | never[]) & (string[] | never[] | undefined);
}
How can I resolve this in Typescript?
6 Replies
Jasmin
Jasmin16mo ago
hm it seems that typescript doesn't know that in this case, the merged props will 100% have a arrayOfStrings property thinkies I don't know if that could be fixed by solid.js. This would be a workaround for you:
interface ComponentProps {
arrOfStrings?: string[]
}

interface FinalProps {
arrOfStrings: string[]
}

export default function Component(props: ComponentProps) {
const merged: FinalProps = mergeProps(
{
arrOfStrings: [],
},
props,
)
// ... etc
}
interface ComponentProps {
arrOfStrings?: string[]
}

interface FinalProps {
arrOfStrings: string[]
}

export default function Component(props: ComponentProps) {
const merged: FinalProps = mergeProps(
{
arrOfStrings: [],
},
props,
)
// ... etc
}
captaindaylight.
captaindaylight.OP16mo ago
The problem is this is a simplified version, so I could have final props but I'm trying to avoid duplicating a large interface :/ Thank you for this answer though
Jasmin
Jasmin16mo ago
oh it's because of the empty array. This also solves the problem:
interface ComponentProps {
arrOfStrings?: string[]
}

export default function Component(props: ComponentProps) {
const merged = mergeProps(
{
arrOfStrings: [] as string[],
},
props,
)
// ... etc
}
interface ComponentProps {
arrOfStrings?: string[]
}

export default function Component(props: ComponentProps) {
const merged = mergeProps(
{
arrOfStrings: [] as string[],
},
props,
)
// ... etc
}
very confusing why typescript thinks the property can be undefined if you provide a default empty array
captaindaylight.
captaindaylight.OP16mo ago
ah yes, that did it! thank you
Jasmin
Jasmin16mo ago
glad that I could help! I asked in the #typescript channel about it (https://discord.com/channels/722131463138705510/783844647528955931/1143634436240461824) This looks like it could be a mistake on solid's side. I will open an issue if this would be the case.
captaindaylight.
captaindaylight.OP16mo ago
awesome I'll track it there!
Want results from more Discord servers?
Add your server