我有两个主题对象:
const lightMode = {
background: "white",
text: {
primary: "dark",
secondary: "darkgrey"
},
} as const
const darkMode = {
background: "black",
text: {
primary: "white",
},
} as const如果lightMode对象(每个人都会首先修改的默认主题)不具有与darkMode对象相同的形状,我希望得到一个类型错误。
这将帮助人们记住使用一些颜色值更新darkMode,如果他们向lightMode添加了一些新的主题颜色。
发布于 2022-08-25 05:54:16
你想得太多了。
两个对象都必须实现的类型才是正确的。就像类型记录中的大多数东西一样,预先定义好的数据类型会使事情从长远来看变得更好。
制作一种类似于:
type UITheme = {
background: string,
text: {
primary: string
secondary: string
}
}现在使用它来确保您的对象是正确的。
const lightMode: UITheme = {
background: "white",
text: {
primary: "dark",
secondary: "darkgrey"
},
} as const
const darkMode: UITheme = {
background: "black",
text: {
primary: "white",
},
} as const
// Property 'secondary' is missing in type
// '{ readonly primary: "white"; }'
// but required in type
// '{ primary: string; secondary: string; }'.或者,如果需要推断字符串文本类型,则使用泛型函数创建对象并强制执行这些类型。
type UITheme = {
background: string,
text: {
primary: string
secondary: string
}
}
const createUIMode = <T extends UITheme>(theme: T) => theme
const lightMode = createUIMode({
background: "white",
text: {
primary: "dark",
secondary: "darkgrey"
},
} as const)
const darkMode = createUIMode({
background: "black",
text: {
primary: "white",
},
} as const)
// error发布于 2022-08-25 05:36:42
这是我的第一次尝试:
type NormalizeThemeConstType<someTheme extends object> = Writable<
Schema<someTheme, string>
>;
const testAssignment: NormalizeThemeConstType<typeof darkMode> =
lightTheme as NormalizeThemeConstType<typeof lightMode>;类型错误一开始看起来很疯狂,但通常情况是,看看错误的结尾,我们的主题之一丢失了另一个的属性!
https://stackoverflow.com/questions/73482285
复制相似问题