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

Accessing property with bracket notation can sometimes incorrectly return an implicit any type #45985

Open
Brqqq opened this issue Sep 21, 2021 · 2 comments
Labels
Bug A bug in TypeScript
Milestone

Comments

@Brqqq
Copy link

Brqqq commented Sep 21, 2021

Bug Report

πŸ”Ž Search Terms

implicit any, property access

πŸ•— Version & Regression Information

  • This changed between versions 4.2.3 and 4.3.5

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const obj = {
	A: 1,
	B: 1
};

// Ignore the implementation, it's about the inferred return type of the function, which should be "A" | "B"
const getRandomKey = () => Math.random() > 0.5 ? "A" : "B"

type Foo =  ReturnType<typeof getRandomKey> extends keyof typeof obj ? ReturnType<typeof getRandomKey> : never;

const randomKey = getRandomKey();
const casted: Foo = getRandomKey();
	
const randomKeyResult = obj[randomKey];
const castedResult = obj[casted];

πŸ™ Actual behavior

randomKeyResult has type 'number', but castedResult has type any

πŸ™‚ Expected behavior

Both randomKeyResult and castedResult should be type number.

If you look at the type of casted and randomKey, the types are identical: "A" | "B". Yet when using them to access a property, they behave differently. Note that in 4.2.3, this expected behavior was also the actual behavior.

@Chetan-unbounce
Copy link

looks like something changed in newer version where they are interpreting this line outputs differently
type Foo = ReturnType<typeof getRandomKey> extends keyof typeof obj ? ReturnType<typeof getRandomKey> : never;
if I change this to
type Foo = ReturnType<typeof getRandomKey>;
type of casted and randomKey both are numbers.
OR
if i type cast it at access time
type t = ReturnType1<typeof getRandomKey>; const castedResult = obj[casted as t];

@andrewbranch andrewbranch added Needs Investigation This issue needs a team member to investigate its status. Bug A bug in TypeScript and removed Needs Investigation This issue needs a team member to investigate its status. labels Sep 23, 2021
@andrewbranch andrewbranch added this to the Backlog milestone Sep 23, 2021
@whzx5byb
Copy link

It seems that this has been fixed in 4.9.5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

4 participants