【发布时间】:2019-08-15 12:23:26
【问题描述】:
请看下面的 TypeScript sn-p。 为什么这不会引发编译错误?这显然不是类型错误吗?我必须更改什么才能使其再次成为类型安全的? TYVM
type A<P> = {
p?: never,
q?: Partial<P>
}
type B<P> = {
p?: Partial<P>
q?: never
}
type C<P> = A<P> | B<P>
const c: C<{ a: number}> = {
p: {
a: 1,
b: 2 // <------ Why is this allowed?!?
}
}
console.log(c)
点击here观看演示
【问题讨论】:
-
允许是因为
{ a: number, b: number }类型与{ a: number }兼容。 -
不,这是错误的@Paleo
-
简化为:typescriptlang.org/play/… - 所以它与
Partial<T>或空值无关。 -
我设法将问题简化为以下情况: const c: { p: { a: number } } | string = { p: { a: 1, b: 2, // 由于某种原因没问题 } } const d: { a: number } | string = { a: 1, b: 2, // ERROR is now detected } 基本上,当您制作嵌套对象时,类型推断会变得很奇怪。这不是我第一次看到类型推断的问题。当您将对象传递给函数时也会发生这种情况。
-
@WayneC 我反对它是重复的:与接口/继承/索引器无关。
标签: typescript types typescript-typings