Reputation: 7340
I've tried this every which way I can think of, and I did look at other similar posts regarding recursive types, but I haven't been able to create a type that works recursively for this case.
What I want is for this type to accept partial properties of CSSStyleDeclaration
, and, for any properties not matching a property of CSSStyleDeclaration
, I want it to map back to the type itself.
This seems to work only for the first level:
interface NestedCSSDeclarations {
[name: string]: CSSDeclaration;
}
type CSSDeclaration = {
[P in keyof CSSStyleDeclaration]?: CSSStyleDeclaration[P];
} & NestedCSSDeclarations
function css(obj: CSSDeclaration) {
// ...
}
let style = {
headline: css({
color: "red",
h1: {
color: "blue",
"&:hover": {
color: "green"
}
},
"@media screen and (min-width: 400px)": {
h1: {
fontSize: "50px"
}
}
})
}
Is there no way to type-hint this?
Upvotes: 1
Views: 596
Reputation: 2573
If you use |
operator instead of &
it will work fine
type CSSDeclaration = {
[P in keyof CSSStyleDeclaration]?: CSSStyleDeclaration[P];
} | NestedCSSDeclarations
Upvotes: 2