Closed
Description
TypeScript Version: 3.7.2
Search Terms: ts2345 derivated type error
I really don't know how to describe this bug in short terms.
Code
enum A {
a = 'a',
b = 'b'
}
interface ObjA {
prop1: string;
}
interface ObjB {
prop2: number;
}
type PayloadMap = {
[A.a]: ObjA;
[A.b]: ObjB;
}
type Content<T extends A> = {
type: T;
payload: PayloadMap[T];
}
function processContent<T extends A>(content: Content<T>) {
parserPayload[content.type](content.payload);
// ^=========== here is the error
}
const parserPayload: { [key in A]: (payload: PayloadMap[key]) => any } = {
// ^============ because this is treated
// as an intersection
a: payload => payload.prop1,
b: payload => payload.prop2,
}
Expected behavior: To correctly know that PayloadMap[key]
is in fact the same as PayloadMap[T]
since key
matches T
.
Actual behavior:
Argument of type 'PayloadMap[T]' is not assignable to parameter of type 'ObjA & ObjB'.
Related Issues:
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
fatcerberus commentedon Dec 10, 2019
Indexed access produces intersection type => most likely caused by #30769.
RyanCavanaugh commentedon Dec 10, 2019
TS doesn't know that this is OK to do. You could have written this, which would be seen equivalently:
RyanCavanaugh commentedon Dec 10, 2019
Duplicate #31445
lgraziani2712 commentedon Dec 10, 2019
BTW, isn't that a kind of bug that TS doesn't check? There are a lot of business logic bugs with correct typings that TS isn't able to catch and that's OK. Isn't the bug you're exemplifying one of that kind?
Thank you for your rapid response!
RyanCavanaugh commentedon Dec 10, 2019
That's a type error, not a business logic error. You can construct examples that observe a
string
where anumber
is expected, for example.