Closed
Description
Bug Report
π Search Terms
generic subtype, generic constraint
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about generic subtypes
β― Playground Link
(strict settings)
Playground link with relevant code
π» Code
interface ContainerBase {
success: boolean;
item: {
itemId: string;
};
}
interface MyContainer {
success: boolean;
item: {
itemId: string;
thing: {
color: string;
size: number;
};
}
}
function getItemAndCheck<ContainerT extends ContainerBase>(container: ContainerT): ContainerT["item"] {
if (!container.success) {
throw new Error(`container success fail`);
}
//return container.item; // good code
return {itemId: "id"}; // bad code, but tsc raises no error.
// The error could be (for example): '{itemId: "id"}' is assignable to the constraint of type 'ContainerT["item"]',
// but 'ContainerT["item"]' could be instantiated with a different subtype of constraint '{itemId: "id"}'
// (like existing errors about generic subtypes)
}
const item = getItemAndCheck(fetchMyContainer());
console.log(item.thing.color); // throws an error at runtime but tsc raised no error earlier
// the caller thinks 'item' is the property of the specific subtype MyContainer but inside
// getItemAndCheck() you can return any subtype not just that one.
function fetchMyContainer(): MyContainer {
// example
return {
success: true,
item: {
thing: {
color: "green",
size: 42,
},
itemId: "id",
}
}
}
π Actual behavior
No error but there should have been.
π Expected behavior
An error on the return statement of getItemAndCheck().
Use case
A rest api which returns data with very similar top level structure, but with differing nested properties, and wanting to write generic handlers for all responses.
Workaround
One could make the properties of the generic themselves generic type parameters as well, but this becomes more difficult the more complex the types are or if you want to manipulate several different properties in a generic way instead of one.