Skip to content

Type 'true' constants behave differently than 'true' literal #29323

Closed
@ooflorent

Description

@ooflorent

TypeScript Version: 3.3.0-dev.20190108

Search Terms:

  • type true
  • type propagation
  • type inference
  • constant condition
  • constant folding

Code

declare const __TRUE__: true;
function ensureValue<T>(value: T | null): T {
  if (__TRUE__) {
    if (value === null) {
      throw new Error();
    }
  }
  return value;
}

Expected behavior:

ensureValue has a correct return type when strictNullChecks is enabled.

In other words, if a constant is typed as true, I expect it to behave like true literal.

declare const __TRUE__: true
if (true) {
if (__TRUE__) {

In the above example, both if statements should infer the types the same way.

Actual behavior:

There is a type error when strictNullChecks is enabled:

$ tsc --strictNullChecks --noEmit test.ts
test.ts:8:3 - error TS2322: Type 'T | null' is not assignable to type 'T'.
  Type 'null' is not assignable to type 'T'.

8   return value;
    ~~~~~~~~~~~~~


Found 1 error.

Please note that if (true) works as expected.

Playground Link:

http://www.typescriptlang.org/play/#src=function%20ensureValue%3CT%3E(value%3A%20T%20%7C%20null)%3A%20T%20%7B%0D%0A%20%20if%20(true)%20%7B%0D%0A%20%20%20%20if%20(value%20%3D%3D%3D%20null)%20%7B%0D%0A%20%20%20%20%20%20throw%20new%20Error()%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%20%20return%20value%20%2F%2F%20OK%0D%0A%7D%0D%0A%0D%0Adeclare%20const%20__TRUE__%3A%20true%0D%0A%2F%2F%20Same%20error%20using%20variable%20declaration%3A%0D%0A%2F%2F%20const%20__TRUE__%3A%20true%20%3D%20true%0D%0Afunction%20ensureValueWithConstant%3CT%3E(value%3A%20T%20%7C%20null)%3A%20T%20%7B%0D%0A%20%20if%20(__TRUE__)%20%7B%0D%0A%20%20%20%20if%20(value%20%3D%3D%3D%20null)%20%7B%0D%0A%20%20%20%20%20%20throw%20new%20Error()%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%20%20return%20value%20%2F%2F%20Hmm%0D%0A%7D

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixedDomain: Control FlowThe issue relates to control flow analysis

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions