【发布时间】:2018-03-28 15:13:27
【问题描述】:
我正在使用JSS 并想定义一个具有强类型键和值的style 对象,而不用两次定义键。
第一次尝试:
const style: Record<string, CSSProperties> = {
root: {
background: 'red'
},
title: {
fontWeight: 'bold'
},
...
}
现在style 不是强类型的,所以编译器在访问style.nonExistingKey 时不会给出警告。
第二次尝试:
如果我像这样明确指定键:
const style: Record<'root' | 'title' | ... , CSSProperties> = {
root: {
background: 'red'
},
...
}
然后我得到一个强类型记录,即style.nonExistingKey 会抛出一个错误。但是,此方法需要复制记录键,因为它们必须显式添加为通用参数。
第三次尝试:
我可以使用以下代码在事后创建一个强类型记录:
const styleObj = {
root: {
background: 'red'
},
title: {
fontWeight: 'bold'
},
...
}
const style = styleObj as Record<keyof typeof styleObj, CSSProperties>
但是,我失去了对记录的 CSSProperties 值的类型检查,所以这不是一个好的解决方案。
有没有办法做这样的事情:
const style: Record<T, CssProperties> = {
root: {
background: 'red'
},
...
}
并让T 被自动推断为'root' | 'title' | ... 等?
【问题讨论】:
-
Record来自哪里? -
是内置的TS类型,
type Record<K extends string, T> = { [P in K]: T; } -
属性名称从何而来?我的意思是
title、root等等。他们来自哪里?他们在某处列出吗?现在您正在基于string定义一个记录,所以当然,任何字符串都可以作为键。 -
我将属性名称声明为
style-object 的一部分,并希望在以后使用它们的强类型。
标签: typescript