【发布时间】:2020-06-07 18:31:00
【问题描述】:
假设我有对象:
const styles = { product: { color: 'blue' } };
由此推断出对象类型,我可以毫无问题地访问foo.bar.baz。
但是,如果我想要类型检查,我需要类似的东西:
import type CSS from 'csstype';
type StyleSheet = Record<string,CSS.Properties>;
const styles:StyleSheet = {
product: { color: 'blue' }
};
上面的内容是有效的,但是,当访问 styles 时,我会得到定义的 styles.whatever.color 或 styles.product.margin,这是不希望的。
考虑到这一点,Typescript 中是否有任何方法可以在输入对象后推断其原始类型,以便我可以访问其真实属性,如下所示:
const styles:StyleSheet = { product: { color: 'blue' } }; // typed as 'StyleSheet' so I get type-checking
styles.whatever.margin // TS thinks this is valid because of the index signature;
const original = styles as OriginalObject; // infer original type so only real properties are accessible
original.whatever // invalid (expected)
original.product.color // valid
export default original;
更新
回复@jcalx的:
【问题讨论】: