Skip to content

Unsoundness in coercion from object to boolean #31464

@uhyo

Description

@uhyo

TypeScript Version: 3.4.3, typescript@3.5.0-dev.20190518

Search Terms: unsound coercion object boolean

Code

const obj: { toFixed: unknown } = 0;
// val has type "123"
const val = obj && "123";
console.log(val.slice()); // <- runtime error!

Expected behavior:
Compile error.

Actual behavior:
This code compiles and causes a runtime error when run.

TypeScript assumes that any value with object type (except {}) is truthy, but it's not true as illustrated above. If one of 0, "", false or 0n is assignable to an object type, it should not be considered truthy.

Playground Link: https://www.typescriptlang.org/play/#src=const%20obj%3A%20%7B%20toFixed%3A%20unknown%20%7D%20%3D%200%3B%0A%2F%2F%20val%20has%20type%20%22123%22%0Aconst%20val%20%3D%20obj%20%26%26%20%22123%22%3B%0Aconsole.log(val.slice())%3B%0A%0A%0A

Related Issues: #18196 (fixed by #27157)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions