gpt4 book ai didi

JavaScript 可选链动态属性

转载 作者:行者123 更新时间:2023-12-01 14:59:52 24 4
gpt4 key购买 nike

我正在尝试使用 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)来映射您的主题对象并通过编译器类型检查。

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

关于JavaScript 可选链动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59682879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com