Skip to content

Type assignable to index access of constraint of type parameter is incorrectly assignable to the index access itselfΒ #46076

Closed
@paulnelson2

Description

@paulnelson2

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.

Metadata

Metadata

Assignees

Labels

Design LimitationConstraints of the existing architecture prevent this from being fixedDomain: Indexed Access TypesThe issue relates to accessing subtypes via index access

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions