microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.42k stars 12.42k forks source link

Assigning to `unknown` / `{}` doesn't change its inferred type #60092

Open rChaoz opened 2 days ago

rChaoz commented 2 days ago

πŸ”Ž Search Terms

type inference, fail, unknown, {}, assign, inferred type

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.0-dev.20240928#code/GYVwdgxgLglg9mABFApgZygRgBQA8Bci4A1mHAO5gCUiA3gFCJOK6IC8iARGnALbpQATjDABzTo2a4AdABsUYqAAt6AX3r1QkWAmQCATHkK1VNBsxbsuPfhmFiJFmfMUr1m8NHhJUGAMxGiHYioogAPohgILwARiiC4YgxcHDyAIZIEVGysongACYowCIo+YlwMQBWKNCJaACesamJANoAuokAbnAwZVkonfGJMTCiIlBmkkysHNx8AvbiUyxyCqLKakA

πŸ’» Code

function test1(x: unknown) {
    x = "somestring"
    x.length // error: Object is of type unknown
}

function test2(x: {}) {
    x = "somestring"
    x.length // error: Property 'length' does not exist on type '{}'
}

function test3(x: string | number | boolean | null | undefined | object | symbol | [] | void | never | bigint) {
    x = "somestring"
    x.length // no error, x is inferred as string
}

πŸ™ Actual behavior

It doesn't change inferred type of x when it is assigned.

πŸ™‚ Expected behavior

It should.

MartinJohns commented 2 days ago

Duplicate of #43584 / #27706.