我无法理解使用泛型参数访问映射类型时的类型脚本行为,这里是触发错误的最简单代码:
export type mockInstances = {
app: {
id: number;
code: string;
};
setup: {
id: number;
code: string;
};
};
type MockEntityName = keyof mockInstances;
type MockInstance<EntityName extends MockEntityName> =
mockInstances[EntityName];
const testWrapper = <EntityName extends MockEntityName>() => {
//Errors
const a: Partial<MockInstance<EntityName>> = {
id: 1,
};
const b: Partial<MockInstances[EntityName]> = {
id: 2,
};
console.log('ab', a, b);
//Error: Type '{ id: 1; }' is not assignable to type 'Partial<MockInstance<EntityName>>'.ts(2322)
//Works
const c: Partial<MockInstance<'app'>> = {
id: 1,
};
const d: Partial<MockInstances['app']> = {
id: 2,
};
const e: Partial<MockInstances[mockEntityName]> = {
id: 2,
};
console.log('cde', c, d, e);
};
我期望TypeScrip编译器能够使用EntityName参数(作为索引或类型参数)将a和b"赋值"给索引类型.
下面是这种奇怪的打字行为的简化版本:
export type mockInstances = {
setup: {
id: number;
code: string;
entityName: string;
desc: string;
};
};
type MockInstance<EntityName extends 'setup'> = mockInstances[EntityName];
const testWrapper = <EntityName extends 'setup'>(entityName: EntityName) => {
//Error: Type '{ id: 1; code: "test"; entityName: EntityName; }'
// is not assignable to type 'Partial<MockInstance<EntityName>>'.ts(2322)
const a: Partial<MockInstance<EntityName>> = {
id: 1,
code: 'test',
entityName,
};
const b: Partial<MockInstance<'setup'>> = {
id: 1,
code: 'test',
entityName,
};
console.log(a, b);
};
所以我缩小了范围,在处理泛型时,Partial的行为并不像我期望的那样,我担心这可能会被认为是一个错误……
谢谢你对这个问题的任何启发.