感谢您查看我的打字稿问题。
为简单起见,我对打字稿“过度属性检查”行为有疑问。我想确保 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;
Run Code Online (Sandbox Code Playgroud)
提前致谢 <3
听起来你想要一个Exact类型。打字稿没有附带,但很容易制作:
type Exact<A, B> = A extends B
? B extends A
? A
: never
: never
Run Code Online (Sandbox Code Playgroud)
这基本上说,如果和A extends B 和 B extends A随后类型是相同的,无论是一个子集或其它的超集。所以它应该允许该类型通过。如果它们不相同,则类型是never阻止该类型被允许的类型。
现在你只需要让你的函数通用,并将该参数强制为正确的类型:
function func<T>(param: Exact<T, LayoutType>) {
console.log(param);
}
func(badData)
// Argument of type '{ margin: number; padding: number; }'
// is not assignable to parameter of type 'never'.
Run Code Online (Sandbox Code Playgroud)
更多相关阅读请参见Typescript 问题 #12936
最后,对象字面量不起作用而对象变量起作用的原因是该字面量是为特定类型构造的。Typescript 无法知道额外的属性,因为这些属性没有类型信息。所以打字稿程序不能使用这些属性,因为它们没有被声明为存在。
然而,当对象是一个变量并且额外的属性是已知的,那么它是一个独立但兼容的类型。额外的属性不能用在只接受窄类型的函数中,但在其他知道更宽类型的代码中可以使用这些属性。
这就是为什么这是有效的:
const obj1 = { a: 1, b: 2 }
const obj2: { a: number } = obj1
console.log(obj1.b) // b can still be accessed
Run Code Online (Sandbox Code Playgroud)
但这不是:
const obj1: { a: number } = { a: 1, b: 2 }
// ^ type error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
462 次 |
| 最近记录: |