Last active
May 15, 2020 10:57
-
-
Save slackday/7142251cf2bb3660f8c24492aa1f700d to your computer and use it in GitHub Desktop.
Typescript/styled-components/no-explicit-any question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Project 1: | |
// Styled componet wrapper might look like this | |
const styledFactory = ( | |
target: any, | |
displayName: string, | |
...systemFunctions: styleFn[] | |
): any => { | |
const Component = styled(target)` | |
min-width: 0; | |
${sx} | |
${compose(animation, color, flexbox, layout, space, ...systemFunctions)} | |
`; | |
Component.displayName = displayName; | |
return Component; | |
}; | |
//----- | |
// Project 2 tries to use same function but with Typescript | |
// But with typescript lint rule "no-explicit-any" | |
// Disallow usage of the any type | |
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-explicit-any.md | |
// Same component becomes wild goose chase of finding the right types for dependencies | |
const styledFactory = ( | |
target: AnyStyledComponent, | |
displayName: string, | |
...systemFunctions: ThemedStyledFunction[] | |
): AnyStyledComponent => { | |
const Component = styled(target)` | |
min-width: 0; | |
${sx} | |
${compose(animation, color, flexbox, layout, space, ...systemFunctions)} | |
`; | |
Component.displayName = displayName; | |
return Component; | |
}; |
Hey Max thanks a lot for taking your time providing me with thorough examples. It's all starting to make much more sense to me. Not to get stuck on lint errors so it's a good idea to document Todo and come back to it later.
I really like the generic return type option. Thinking about it. This probably solves 9/10 issues I have had in the past. Often the use case is just to return whatever the underlying method returns (in the dependency). And this approach seems like the appropriate way of handling it in a clean way 💯 👍
I also got the tips on hackernews to look into *.d.ts
files which I was unaware of. Again thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A more advanced trick for the HOC case is the
ReturnType<T>
generic option, where you use Typescript's inferencing engine directly in finding out what the return type of something else is.Because you are simply returning what
styled()
itself returns, you can ask Typescript for theReturnType
of (thetypeof
) that function.