Skip to content

Reassigning of inferred object with Indexed access value does not widen it's typeΒ #63514

@svenvandescheur

Description

@svenvandescheur

πŸ”Ž Search Terms

Type Inference
Indexed Access Types
object type
keyof object
type assertion
control flow narrowing
type widening
no implicit any

πŸ•— Version & Regression Information

?

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/FAMwrgdgxgLglgewgAgCYFN0AcDi6YAUAFgIYCeAzjCVANYBcyCARgFbqwA0yWJMRjKgCc4EAOYBKZAG9gyZFCRVkFDvCXIAvDz5EAdBSwAbOIQBEesxIDcc5EfwKwQoeggwAymsQRBMEeLW8gD0wcge-qJi3BAIMMgQHFDoFBQkIkZkyCTItOhkCCBMbGp6dg7xAG4kRmDoWsiklNR0QcihyACSECDoLuioxeywwHYA7kRwDsgEqrA+FHoO4vxSsvLyUM6u7l7zSA1z6hCLFJMghFIAPlfIZmZtHREB0QlxCUkpaRlZOXkFRRYwxgZQ2CiU8X+DS2-V23gOJAouXyhWQMDIWHQqOqtXq7TCABUMRxEfEAAb-MlohDIZj1P75ZBkoFqMncUwAciROLqyFcAFsSKIkbFIbExhBQRsefVtDKANr-AC6jzCMpURAQYCMqEARIS0+kQLIEBBCZCQWjiiDcU0fSp9AD8UmYWXF2SR-D69TgIppY3I1LR6CMRjRRHqin6sDRxIddgAvnZXDBnCgZaqmTK2chWGBlIimCgTIlkABGAAMyB9VZ6fVcgwLzJKsGz6HtKH4WrERFproQYyrMC5MywCFScGYmSkFAQ-Pwk3EyGDqjKieAHQJkyR1c9NawYHiLOjeYGyBAtpgKXg4jKihOh7YDXWG3PCEYz7B8mY6UYZm-QjMOx5ETNc72UVA+BybQMGwPBCCBbgzFfPR-ysEIwjJCDqCpasxlMTUD3BfljCFdwY0xBskSbYEyWAMCEAcJYEDEAh0UxVEsJIbhOKkfFGn7Ns+kLPlIHgOd2XiFMhBOJhCM5KjhCiMk9CAA

πŸ’» Code

function deepGet(haystack: object, path: string) {
  const sections = path.split(".");
  let currentSection: string;  // String, not neccessarily a keyof object.
  let value = haystack;  // Inferred object

  while (sections.length) {
    currentSection = sections.shift() || "";  // String, not neccessarily a keyof object.
    const key = currentSection as keyof typeof value  // Typecast `key` to be a key `object`, it's value remains any/unknown.
    value = value[key];  // value shouldβ„’ be any/unknown by now as there is no way to tell the correct type?
  }
  return value;  // `value`, just as on line 10 is inferred as `object`, even though by now it's (possibly) something else.
}

// This is the input object used for testing.
const obj = {
    foo: {
        bar: "bar"
    }
}

const data = deepGet(obj, "foo.bar")  // `data` is without complaint typed as `object`
console.log(typeof data, data)  // however on runtime, it turns out it's `string`.

πŸ™ Actual behavior

let value: object

πŸ™‚ Expected behavior

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions