Since you only want fields that already exist in A, you should consider using another approach, e.g.:
type IsAssignable<X, Y extends X> = {
[K in keyof Y]: K extends keyof X ? Y[K] : never;
}
type B = IsAssignable<A, { name: string; }>;
This wouldn't stop you from declaring
type C = IsAssignable<A, {
name: string;
foo: number;
}>;
// C becomes { name: string; foo: never }
But it's still type-safe! Essentially, IsAssignable<X,Y>
is telling typescript to ignore fields that aren't present in X
. So any function that expects A
should still accept C
gladly;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…