【问题标题】:JavaScript optional chaining dynamic propertyJavaScript 可选链动态属性
【发布时间】:2020-04-28 04:11:31
【问题描述】:

我正在尝试访问由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') //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]

【问题讨论】:

  • 你到底是怎么得到这个错误的,我无法重现它。
  • 您需要一个允许可选链接的环境。然后只需使用主题?.headers?.['h1']?.color ?? '#000'

标签: javascript typescript styled-components optional-chaining


【解决方案1】:

您可以创建一个接口来映射您的主题对象并通过编译器类型检查。

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

【讨论】:

  • 有趣的想法,为它定义类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2020-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
相关资源
最近更新 更多