Issue
I need to make a recursive style object, that can support style properties and in a nested format.
I have a super hard time wrapping my head around this, and I've tried pretty much all solutions I could find here on SO and google.
interface Properties {
border?: string;
width?: string;
}
//# 1 Type attempt
type TRecursiveProperties = Properties & {
[index: string]: TRecursiveProperties;
};
//# 2 Interface attempt
interface IRecursiveProperties extends Properties {
[index: string]: IRecursiveProperties;
}
const test: TRecursiveProperties = {
border: '1px solid green',
isActive: {
border: '2px solid red',
'&:hover': {
border: '3px solid blue'
}
}
};
I'd expect the Recursive properties to be a fallback/catch all or some way to exclude keys from Properties object.
The 2 errors I get are either
Type alias 'TRecursiveProperties' circularly references itself.
Property 'width' of type 'string' is not assignable to string index type 'IRecursiveProperties'
Any ideas how I can achieve that?
Solution
I would go for this:
interface Properties {
width?: string;
border?: string;
[selector: string]: string | Properties | undefined;
}
const myStyles: Properties = {
'width': '100px',
' .child': {
'width': '200px',
'border': '1px color blue',
'&:hover': {
border: '1px solid aquamarine',
},
},
};
In this typescript resource: https://basarat.gitbook.io/typescript/type-system/index-signatures, search for 'Design Pattern: Nested index signature' to see a pretty similar example.
Answered By - Sergeon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.