TypeScript: Property does not exist on type '{}'

后端 未结 7 1785
忘掉有多难
忘掉有多难 2021-01-31 13:25

I am using Visual Studio 2013 fully patched. I am trying to use JQuery, JQueryUI and JSRender. I am also trying to use TypeScript. In the ts file I\'m getting an error as follo

相关标签:
7条回答
  • 2021-01-31 13:39

    I suggest the following change

    let propertyName =  {} as any;
    
    0 讨论(0)
  • 2021-01-31 13:43
    myFunction(
            contextParamers : {
                param1: any,
                param2: string
                param3: string          
            }){
              contextParamers.param1 = contextParamers.param1+ 'canChange';
              //contextParamers.param4 = "CannotChange";
              var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
              contextParamers2.param4 =  'canChange';
              return contextParamers2;
          }
    
    0 讨论(0)
  • 2021-01-31 13:44

    You can assign the any type to the object:

    let bar: any = {};
    bar.foo = "foobar"; 
    
    0 讨论(0)
  • 2021-01-31 13:53

    Access the field with array notation to avoid strict type checking on single field:

    data['propertyName']; //will work even if data has not declared propertyName
    

    Alternative way is (un)cast the variable for single access:

    (<any>data).propertyName;//access propertyName like if data has no type
    

    The first is shorter, the second is more explicit about type (un)casting


    You can also totally disable type checking on all variable fields:

    let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
    untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking
    

    Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped

    0 讨论(0)
  • 2021-01-31 14:01
    let propertyName= data['propertyName'];
    
    0 讨论(0)
  • 2021-01-31 14:03

    When you write the following line of code in TypeScript:

    var SUCSS = {};
    

    The type of SUCSS is inferred from the assignment (i.e. it is an empty object type).

    You then go on to add a property to this type a few lines later:

    SUCSS.fadeDiv = //...
    

    And the compiler warns you that there is no property named fadeDiv on the SUCSS object (this kind of warning often helps you to catch a typo).

    You can either... fix it by specifying the type of SUCSS (although this will prevent you from assigning {}, which doesn't satisfy the type you want):

    var SUCSS : {fadeDiv: () => void;};
    

    Or by assigning the full value in the first place and let TypeScript infer the types:

    var SUCSS = {
        fadeDiv: function () {
            // Simplified version
            alert('Called my func');
        }
    };
    
    0 讨论(0)
提交回复
热议问题