我正在尝试在我的打字稿代码中创建一个新类型,如下所示:
interface required {
x: string
}
interface optional1 {
y: string
}
interface optional2 {
z: string
}
type combined = required & (optional1 | optional2)
我想要的行为是:
您需要在可选接口中将属性标记为可选,方法是使用?
。
如果你这样做,你的定义是有效的,除了允许一个对象同时具有y
和z
属性(type combined = (required & optional1) | (required & optional2);
也是如此,这让我感到惊讶):
interface required {
x: string
}
interface optional1 {
y?: string // Note the ?
}
interface optional2 {
z?: string // Note the ?
}
type combined = required & (optional1 | optional2);
function foo(x: combined): void {
}
foo({ x: "x" }); // Works
foo({ x: "x", y: "y" }); // Works
foo({ x: "x", y: "y", z: "z" }); // Works
foo({ x: "x", q: "q" }); // Error because of q
foo({ y: "y" }); // Error because there's no x