error TS2339: Property 'x' does not exist on type 'Y'

前端 未结 6 1217
忘掉有多难
忘掉有多难 2020-12-01 12:02

I don\'t understand why this code generates TypeScript error. (It\'s not the original code and is a bit derived, so please ignore the non-sense in the example):



        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:33

    The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:

    (Hacky) Workaround 1

    You can assign the object to a constant of type any, then call the 'non-existing' property.

    const newObj: any = oldObj;
    return newObj.someProperty;
    

    You can also cast it as any:

    return (oldObj as any).someProperty;
    

    This fails to provide any type safety though, which is the point of TypeScript.


    (Hacky) Workaround 2

    Another thing you may consider, if you're unable to modify the original type, is extending the type like so:

    interface NewType extends OldType {
      someProperty: string;
    }
    

    Now you can cast your variable as this NewType instead of any. Still not ideal but less permissive than any, giving you more type safety.

    return (oldObj as NewType).someProperty;
    

提交回复
热议问题