简体   繁体   English

JavaScript 可选链接动态属性

[英]JavaScript optional chaining dynamic property

I am trying to access a dynamic property with safety provided by optional chaining that is available in TS.我正在尝试通过 TS 中可用的可选链接提供的安全性访问动态属性。 However it appears that this is not valid.然而,这似乎是无效的。

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 appears that the optional changing will apply to the optional [] as a type but not to the values inside.似乎可选更改将应用​​于可选[]作为类型,但不适用于其中的值。

How can I make this optional without having to do [undefined || someDefaultValue]如何在不必做[undefined || someDefaultValue] [undefined || someDefaultValue] ? [undefined || someDefaultValue] ?

You can create an interface that maps your theme object and pass the compiler type checking.您可以创建一个接口来映射您的主题对象并通过编译器类型检查。

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') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM