使用新的index as
syntax,我可以过滤出如下类型的键.
// Filter out all keys of `T` that do not exist in `U`
type IntersectKeys<T, U> = {
[K in keyof T as K extends keyof U ? K : never]: T[K];
};
// e.g., IntersectKeys<{ foo: string; bar: number}, { foo: never }> === { foo: string }
然而,当我将此类型用于泛型时,TypeScript似乎完全忽略了类型判断.
Is this a TypeScript bug? Is there a way around this?
interface FooBar {
foo: string;
bar: number;
}
function intersectFooBarKeys<U>(fb: FooBar, intersect: U): IntersectKeys<FooBar, U> {
return false; // ---> !!Wrong implementation, but no type error!! <---
}
// Example usage
const fooBar: FooBar = {
foo: 'foo',
bar: 42,
};
const onlyFoo: { foo: string } = intersectKeys(fooBar, { foo: null });
// Based on its type, I would expect `onlyFoo` to be of the form `{ foo: string }`, but it is `false` instead!