JavaScript optional chaining dynamic property JavaScript optional chaining dynamic property typescript typescript

JavaScript optional chaining dynamic property


You can create an interface that maps your theme object and pass the compiler type checking.

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 passconsole.info(theme?.headers?.['h1']?.color ?? '#000')