My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid.
export const theme = {
headers: {
h1: {
},
h6: {
color: '#828286'
},
},
}
console.info(theme?.headers?.['h6']?.color ?? '#000') //will pass
console.info(theme?.headers?.['h1']?.color ?? '#000') //will fail
Error
Identifier expected. TS1003
10 | const StyledTypography = styled.div`
11 | margin: 0;
> 12 | color: #000; ${({theme}) => theme?.headers?.[variant]?.color ?? '#000'}
| ^
13 | `
14 | return (
15 | <StyledTypography as={variant}>
It seems that the optional chaining only applies to the optional []
as a type and not the values inside.
Is there a way to make this optional without resorting to [undefined || someDefaultValue]
?