JavaScript 可选链接动态 属性

JavaScript optional chaining dynamic property

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

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

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