JavaScript可选链接动态属性
我正在尝试访问TS中提供安全性的动态属性。但是,这似乎是无效的JavaScript可选链接动态属性,javascript,typescript,styled-components,optional-chaining,Javascript,Typescript,Styled Components,Optional Chaining,我正在尝试访问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'
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
错误
需要标识符。TS1003
10 | const StyledTypography=styled.div`
11 |余量:0;
>12 |颜色:#000${({theme})=>theme?.headers?[variant]?.color?'#000'}
| ^
13 | `
14 |返回(
15 |
可选更改似乎将作为类型应用于可选的[]
,但不应用于其中的值
如何在不必执行
[undefined | | someDefaultValue]
的情况下将此设置为可选设置?您可以创建一个映射主题对象并通过编译器类型检查的接口
interface Headers {
[key: string]: {
[key: string]: string
}
}
interface Theme {
headers: Headers
}
const theme: Theme = {
headers: {
h1: {
},
h6: {
color: '#828286'
},
},
}
console.info(theme?.headers?.['h6']?.color ?? '#000') //will pass
console.info(theme?.headers?.['h1']?.color ?? '#000')
你到底是如何得到这个错误的,我无法复制它。你需要一个允许可选链接的环境。然后只使用主题?.headers?['h1']?.color???有趣的想法,定义它的类型
interface Headers {
[key: string]: {
[key: string]: string
}
}
interface Theme {
headers: Headers
}
const theme: Theme = {
headers: {
h1: {
},
h6: {
color: '#828286'
},
},
}
console.info(theme?.headers?.['h6']?.color ?? '#000') //will pass
console.info(theme?.headers?.['h1']?.color ?? '#000')