JavaScript 可选链接动态属性

Jam*_*ber 15 javascript typescript optional-chaining styled-components

我正在尝试通过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
Run Code Online (Sandbox Code Playgroud)

错误

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}>
Run Code Online (Sandbox Code Playgroud)

似乎可选更改将应用​​于[]作为类型的可选,但不适用于内部的值。

我怎样才能使这个成为可选而不必做[undefined || someDefaultValue]

haw*_*wks 6

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

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') 
Run Code Online (Sandbox Code Playgroud)