Incorporating a Text component in Typescript offers various type options, such as:
<Text type='h2'>Hello World</Text>
.
Utilizing a styles object with these types as keys allows for deriving the appropriate styles. However, there should be flexibility for multiple type possibilities.
import React from 'react'
import { colors } from '../../config'
const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) => obj[key]
const styles = {
h1: {
fontSize: "46px",
lineHeight: "64px",
fontWeight: 300,
},
h2: {
fontSize: "34px",
lineHeight: "48px",
fontWeight: 300,
},
// Additional style objects...
}
interface Style {
fontSize: string;
lineHeight: string;
fontWeight: number;
}
// Interfaces and Props declaration...
const Text = ({ children, type, color = colors.darkGrey, ellipsis = false, fontWeight }: Props) => {
const style = {
...getKeyValue<keyof Styles, Styles>(type)(styles),
color,
minHeight: 25, // Height to be modified
textOverflow: ellipsis ? 'ellipsis' : 'none',
overflow: ellipsis ? 'hidden' : 'none',
whiteSpace: ellipsis ? 'nowrap' : 'none',
} as React.CSSProperties
if (typeof fontWeight !== 'undefined') {
style.fontWeight = fontWeight
}
return <div style={style} >{children}</div>
}
export default Text
The current implementation requires repeated declaration of style object keys:
- In the styles object itself
- In the Styles interface
- In the declaration of type
type
This redundancy can be optimized, but figuring out an improved approach is challenging due to my limited experience with TypeScript. Any suggestions for a more concise and efficient solution are welcome!