Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript可选链接动态属性_Javascript_Typescript_Styled Components_Optional Chaining - Fatal编程技术网

JavaScript可选链接动态属性

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'

我正在尝试访问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
错误 需要
标识符。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')