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 に答える