我正在尝试使用TS中提供的可选链式操作符来安全地访问动态属性。然而似乎这不是有效的。
我正在尝试使用TS中提供的可选链式操作符,以安全地访问动态属性。然而,似乎这种方法无效。
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
错误
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}>
似乎这个可选项更适用于可选的[]
作为类型,而不是其中的值。
如何使其成为可选项而不必执行[undefined || someDefaultValue]
?