为什么这段代码没有抛出任何错误:
interface X {
a: string;
b?: string;
}
type Y<T> = {
[key in keyof T]: boolean;
}
class A<Definition> {
constructor(public readonly definition: Definition, public readonly fields: Y<Definition>) {
}
}
const y = {
a: true,
c: false
}
const a = new A<X>({a: 'first', b: 'second'}, y)但是这会抛出一个错误吗?
interface X {
a: string;
b?: string;
}
type Y<T> = {
[key in keyof T]: boolean;
}
const y: Y<X> = {
a: true,
c: false,
}我希望有类似于第一个例子的东西抛出一个错误,因为c不是X的键。
如果我在第一个例子中将类型Y<X>添加到y,我会得到一个编译器错误。
发布于 2018-03-07 01:53:15
您可以尝试使用联合类型来使您的第二个示例代码工作:
interface X {
a: string;
b?: string;
}
type Y<T> = {
[key in keyof T]: boolean;
}
type Z = {
c: boolean;
}
const y: Y<X> | Z = {
a: true,
c: false
}https://stackoverflow.com/questions/49136628
复制相似问题