扩展类时,将排除类上对象的类型,并且我可以添加所需的任何属性。我该如何预防?
type StaticObject = {
a: string[];
};
class System {
staticObject?: StaticObject;
}
export default class ToggleInputSystem extends System {
staticObject = { // Should be a type error but none appears
a: ["hi"],
added: true
};
}
https://codesandbox.io/s/typescript-playground-export-ed1vx?file=/index.ts:0-254
答案 0 :(得分:1)
这是由于打字稿中类型解析的性质所致。键入变量时:可以说是一个数字(let a: number
),它可以包含number
的所有子类型。这适用于联合类型(let a: 1 | 2 | 3
)和对象。因此,类型{a: number, b: number}
可以用任何对象实现,只要它的键a和b为number
的子类型。而且,通常不需要阻止类型的进一步特殊化,因为与该接口一起使用的所有函数/类(例如System
)都将具有所有预期的系统属性类型。他们不在乎其余的。
请注意,此规则是一个例外。当您需要一个对象作为函数的参数,并且在函数调用中内联声明它时,打字稿将抛出错误。
function f(options: {duration: number, easing: string}) {}
f({duration: 200, somethingElse: "hi", easing: "ease"}) // Err
let optionsEnhanced = {duration: 200, somethingElse: "hi", easing: "ease"}
f(optionsEnhanced) // No Err
乍一看这似乎令人困惑,但实际上只是警告您,内联声明的选项具有永远不会使用的属性(因为除了函数内部没有任何引用)。