Skip to content

Narrowing type of an object property with type guard does not allow us to assign/return the instance as having a narrower prop type. #32595

Closed
@IKoshelev

Description

@IKoshelev

TypeScript Version: 3.5.1, 3.5.3

Search Terms: guard type-guard property return assignment

Code

type WideProp = {
  prop: (number | string);
}

type NarrowProp = {
  prop: string;
}

function showcase(): NarrowProp {
  const wide: WideProp = {
    prop: 'aaa' as (string | number)
  };

  const guard = (i: (number | string)): i is string => true;

  if(guard(wide.prop)){
    // this works
    const prop: string = wide.prop;

    // this does not?
    let narrow: { prop: string } = wide;

    // and this does not?
    return wide;
  } 
}

Expected behavior:
Successful type guard check narrowing property prop from string | number to string should allow us to return \ assign containing object instance when a { prop: string } type is expected.

Actual behavior:
With successful type guard check we are allowed to assign property prop when string is expected, but assigning \ returning containing instance as { prop: string } is still forbidden.

Playground Link: https://www.typescriptlang.org/play/#code/C4TwDgpgBA6glgEwgBQE4HsxQLxQN4BQUUYGYAXFABQB2ArgLYBGEqUAPlAM7Cpw0BzAJQBuAgF8CBUJCgA5AIaoMAdzSYc+IiTKUefQWMkEAZnRoBjYHHQ1uAC3QqLCrhCpDKi5U-VZCxBa2PFAqiBCU8Eh+mgHEOpiUAOQKqUlQrtT6-AIcUPTMrELa4mLaQTQhAnRKCJpUcJS0jCxsnNmCQp5QcD1c3Lw5OAB8ULx0EGXEcCZU1bVUYUgAdKSYXXHEAPRbY-Zw-SroqADWXNqBwcAJFAMGubhLEKtkU-E7ewdQCOgQ-TToYAAfguUAANhBrjQlKpKHgbnpBoIoOJNE83ttdgoaNdgPt+j8-vlASD4lBUJC6Kg7OiSlAJEA

Related Issues: #3812

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions