Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type guard for child not transitive parent object #58241

Closed
clouds56 opened this issue Apr 18, 2024 · 3 comments
Closed

Type guard for child not transitive parent object #58241

clouds56 opened this issue Apr 18, 2024 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@clouds56
Copy link

🔎 Search Terms

"is not assignable", "ts(2345)"

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about [Type System Behavior](https://github.com/Microsoft/TypeScript/wiki/FAQ#type-system-behavior)

⏯ Playground Link

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFDLJgCeADhAFzIBEc1yAPjQEbUDcByCAFsADYATKBBBUQAVwC2zaAG0Auo2QTp0DgF88JcmkxgAglChxiyALzIA8pOBgAPOiwAaGj35CR1AHzIAZLk43QWFRZSkZKAUNDm0URzAAZTAoUABzc10sPwDCWKpadjx1DjwEAHsQLJgARgyACgB9KnjDY2IASnMfHGLSiqqAJnqmzMTktM6zbt68OrhmvUnuzmAYZDrWkwA6YAxN4jmtoI8Qds78QkJyyrK+CC2+MtTD45CHkVSwbnaOS+QauY-TiaQirdZwLaxcxmCwFc6cQgwAaA37ITS9IA

💻 Code

interface Test {
  type: "a" | "b";
  children: number[] | number;
}
type TestArray = Omit<Test, "children"> & {
  children: number[];
};
type TestString = Test & {
  type: "a";
};

const f1 = (_: TestArray) => {};
const f2 = (_: TestString) => {};

(a: Test) => {
  if (Array.isArray(a.children)) {
    console.log(a.children.length);
    f1(a); // type error
  }
  if (a.type === "a") {
    f2(a); // type error
  }
};

🙁 Actual behavior

Complain with error

Argument of type 'Test' is not assignable to parameter of type 'TestArray'.
  Type 'Test' is not assignable to type '{ children: number[]; }'.
    Types of property 'children' are incompatible.
      Type 'number | number[]' is not assignable to type 'number[]'.
        Type 'number' is not assignable to type 'number[]'.ts(2345)
Argument of type 'Test' is not assignable to parameter of type 'TestString'.
  Type 'Test' is not assignable to type '{ type: "a"; }'.
    Types of property 'type' are incompatible.
      Type '"a" | "b"' is not assignable to type '"a"'.
        Type '"b"' is not assignable to type '"a"'.ts(2345)

🙂 Expected behavior

Pass the type check, since we already checked a.children, actually compiler knows typeof a.children is number[] here, why it forget this when we treat a as a whole?

Additional information about the issue

I know we could have a user defined type guards like this

function isTestArray(a: Test): a is TestArray {
  return Array.isArray(a)
}

(a: Test) => {
  if (isTestArray(a)) {
    console.log(a.children.length);
    f1(a); // this passed
  } else {
    console.log(a.children.toFixed()); // but it won't work for the other branch
  }
};
@fatcerberus
Copy link

Duplicate of #42384. Due to various design limitations, type narrowings of object properties currently don't propagate to the containing object except for the special case of discriminated unions.

@clouds56
Copy link
Author

Yes, it is duplicated, I'm not sure it should be discussed here and #42384 .

Type guards do not propagate type narrowings to parent objects. The narrowing is only applied upon access of the narrowed property which is why the destructing function works, but the reference function does not. Narrowing the parent would involve synthesizing new types which would be expensive. More detail in this comment.

If I read correctly, it is due to performance issue so we choose not to implement this?

I dived into source code and createTypeChecker.checkExpression()
src/compiler/checker.ts#L39525

const type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);

I think the performance issue is refer to here we won't like to generate a new type every time we checkExpression, even though actually we already have all related information to construct a coerced type here.

Correct me I'm wrong

In current design when checking if a could be called by f1(_), it would

  1. checkExpression(node: Expression | QualifiedName): first calculate type of a, without checking deep "type relation", so it would give Test as is.
  2. checkTypeRelatedTo(source: Type, target: Type): check if Test is compatible with TestArray, without context of a

I see now getTypeOfSourceProperty: (sym: Symbol) => Type used by propertiesRelatedTo is now setting to getNonMissingTypeOfSymbol, is it possible to switch to an Expression awareable callback on error?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 19, 2024
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Apr 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants