【发布时间】:2020-09-09 14:34:05
【问题描述】:
感谢您查看我的打字稿问题。
为了简单起见,我对打字稿“多余的属性检查”行为有疑问。我想确保 TypeScript 不接受具有额外属性的对象。
OFC 在我的简单界面示例中,我可以简单地选择可用数据,但我有很多属性,我想避免在运行时过滤它们,有什么办法吗?
在这里你可以找到我为这个主题制作的示例代码:
type LayoutType {
margin: number;
}
const badData = {
margin: 23,
padding: 23,
}
function func(param: LayoutType) {
console.log(param);
// Here I want to use property being sure param only contains LayoutType property
}
// OK
func({ margin: 42 })
// OK : padding is detected as unwanted property
func({ margin: 42, padding: 32 })
// KO : bad data shouldn't fit
func(badData)
/* SAME */
// OK : padding is detected as unwanted property
const test1: LayoutType = { margin: 42, padding: 32 };
// KO : bad data shouldn't fit
const test2: LayoutType = badData;
提前致谢
【问题讨论】:
-
不确定你想要什么,因为你已经收到了一个错误
Argument ... is not assignable。如果你想删除不需要的属性,你必须明确地这样做,TS 不会改变你的程序的行为......
标签: typescript