具有成员的通用映射类型约束在一个成员存在时不具有约束

问题描述 投票:0回答:2
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

typescript typescript-generics
2个回答
0
投票

Type'{m:number; }'与类型'{x ?: number |没有共同的属性。未定义y ?:数字|未定义z ?:数字|未定义}。


0
投票

证明这根本与泛型无关:

© www.soinside.com 2019 - 2024. All rights reserved.