typescript检查两个const对象是否具有相同的形状



我有两个主题对象:

const lightMode = {
background: "white",
text: {
primary: "dark",
secondary: "darkgrey"
},
} as const
const darkMode = {
background: "black",
text: {
primary: "white",
},
} as const

如果lightMode对象(默认主题,每个人都会首先修改(与darkMode对象的形状不同,我想得到一个类型错误。

如果人们在lightMode中添加一些新的主题颜色,这将帮助他们记住用一些颜色值更新darkMode。

你想得太多了。

两个对象都必须实现的类型是正确的。像Typescript中的大多数东西一样,从长远来看,预先定义好的数据类型会让事情变得更好。

制作一个类似的类型

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

参见操场

这是我的第一次尝试:

type NormalizeThemeConstType<someTheme extends object> = Writable<
Schema<someTheme, string>
>;
const testAssignment: NormalizeThemeConstType<typeof darkMode> =
lightTheme as NormalizeThemeConstType<typeof lightMode>;

类型错误一开始看起来很疯狂,但通常情况下,从错误的末尾来看,我们的一个主题缺少另一个主题的属性!

相关内容

最新更新