const abc = <T extends object, P extends { [key in keyof T]?: number }>(
a: T,
b: P
) => {
console.log(a, b);
};
const A = { x: "1", y: "2", z: "3" };
const b = { x: 1, y: 2, z: 3 };
const b1 = { x: 1, y: 2 };
const b3 = { m: 5 };
const b4 = { m: 5, x: 1 };
abc(A, b);
abc(A, b1);
abc(A, b3); // Type '{ m: number; }' has no properties in common with type '{ x?: number | undefined; y?: number | undefined; z?: number | undefined; }'
abc(A, b4); // expect type error just like b3 but it is not
由于m
上不存在A
,因此b4
应该像b3
一样出错吗?但是为什么它不是错误以及如何解决?
这里是沙盒codesandbox
Type'{m:number; }'与类型'{x ?: number |没有共同的属性。未定义y ?:数字|未定义z ?:数字|未定义}。
证明这根本与泛型无关: