21

我正在尝试访问具有安全性的动态属性,该安全性由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]

4

1 回答 1

9

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

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') 
于 2020-01-10T13:58:47.597 回答