我最近遇到了以下打字脚本的情况,这种情况在实践中会经常发生:
interface Options {
foo?: number;
bar?: string;
}
const defaultOptions = {
foo: 123,
bar: 'abc',
} as const satisfies Options;
function f(options: Options) {
const fullOptions = { // Type is inferred as {foo: number; bar: string} (regardless of satisfies)
...defaultOptions,
...options,
} as const satisfies Required<Options>; // This is not guaranteed and should be marked as error!
// The actual type is still just Options because the props of defaultOptions may be overwritten.
console.log(fullOptions);
return fullOptions.bar.toUpperCase();
}
f({foo: 456}); // Works
f({foo: 456, bar: undefined}) // Runtime error!
正如您所看到的,TypeScrip在satisfies Required<Options>
部分中没有抱怨,尽管它应该这样做.这是故意的行为还是一个漏洞?