151

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 follows:

Property 'fadeDiv' does not exist on type '{}'.

I think I have the correct references for JQuery, JQueryUI and JSRender for TypeScript, but from what I've read this is looking like a d.ts issue.

There are no errors in JavaScript, but I don't want to have Visual Studio saying there are errors if I can help it. Both times fadeDiv is mentioned in the JavaScript there is a red line under it and both errors say the same thing as above.

/// <reference path="../scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../scripts/typings/jqueryui/jqueryui.d.ts" />
/// <reference path="typings/jsrender/jsrender.d.ts" />

var SUCSS = {};

$(document).ready(function () {
   SUCSS.fadeDiv();
});

SUCSS.fadeDiv = function () {
var mFadeText: number;
$(function () {
    var mFade = "FadeText";
    //This part actually retrieves the info for the fadediv
    $.ajax({
        type: "POST",
        //url: "/js/General.aspx/_FadeDiv1",
        url: "/js/sucss/General.aspx/_FadeDivList",
        //data: "{'iInput':" + JSON.stringify(jInput) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (xhr, status, error) {
            // Show the error
            //alert(xhr.responseText);
        },
        success: function (msg) {
            mFadeText = msg.d.Fade;
            // Replace the div's content with the page method's return.
            if (msg.d.FadeType == 0) {//FadeDivType = List
                var template = $.templates("#theTmpl");
                var htmlOutput = template.render(msg.d);
                $("[id$=lblFadeDiv]").html(htmlOutput);
            }
            else {//FadeDivType = String
                $("[id$=lblFadeDiv]").html(msg.d.FadeDivString);
            }
        },
        complete: function () {
            if (mFadeText == 0) {
                $("[id$=lblFadeDiv]").fadeIn('slow').delay(5000).fadeOut('slow');
            }
        }
    });
});

For those who might read this later, the SUCSS is the namespace. In typescript it appears I would have wanted to do something like this.

$(document).ready(function () {
    SUCSS.fadeDiv();
});
module SUCSS {
    export function fadeDiv () {};
};

So the function is made public by use of the export and I could call the SUCSS.fadeDiv to run on page load by calling it with the SUCSS.fadeDiv();. I hope that will be helpful.

kahlan88
  • 101
  • 1
  • 8
jvcoach23
  • 2,765
  • 10
  • 34
  • 50
  • 1
    You seem to be missing at least the closing `}` brace, and perhaps other code. – mk. Dec 14 '15 at 19:12
  • 2
    You need to get this code down to a self-contained example so that people can actually reproduce the problem. As it stands you have tons of variables in use that don't have definitions, so we can only guess at their types. – Ryan Cavanaugh Dec 14 '15 at 19:22

9 Answers9

174

You can assign the any type to the object:

let bar: any = {};
bar.foo = "foobar"; 
21st
  • 2,011
  • 1
  • 12
  • 14
77

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

Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • 9
    What is the point in using TypeScript if we're just going to circumvent it with hacks like this? – Damien Roche Oct 08 '18 at 08:47
  • 11
    The Typescript type checking is not strict and mandatory, it is like a strong recommendation, you can bypass it any time everywhare by simply add . Often you have to do it since in the web you interact with javascript libraries, untyped json APIS and dynamically generated objects. In cases like these, exceptionally, you have to be able to use functionalities like this, formally this is called reflection, and is a functionality that Java has too, so neither using Java or C# – Luca C. Oct 08 '18 at 10:28
25
let propertyName= data['propertyName'];
Amr Ibrahim
  • 2,066
  • 2
  • 23
  • 47
  • 1
    That was the only one which really solved my compilation issue. Even declaring like section: { year: any }[] made error: Property 'year' does not exist on type '{ year: Number; }[]'. – Paweł Stolka Sep 13 '19 at 15:29
18

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');
    }
};
Fenton
  • 241,084
  • 71
  • 387
  • 401
11

I suggest the following change

let propertyName =  {} as any;
B--rian
  • 5,578
  • 10
  • 38
  • 89
Botond
  • 630
  • 6
  • 9
  • 1
    Welcome to SO, Kovacs! Please edit your answer so that it does contain a short introductory paragraphy which relates to the question asked. In addition to that, a brief explanation would be cool, why your answer solves the issue. – B--rian Aug 06 '19 at 12:58
  • 1
    I like this solution a lot better than the others mentioned. – wvdz May 08 '20 at 15:40
5

You can use the partial utility type to make all of the objects properties optional. https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype

type Foo = {
  bar: string;
}

const foo: Partial<Foo> = {}
foo.bar = "foobar"
Samir Ergaibi
  • 59
  • 1
  • 2
1
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;
      }
1

var SUCSS = {}; implicitly defines the type of SUCSS as an object with no properties. If you want to allow optional properties on it, then you should explicitly define its type.

type SUCESSType = {
    fadeDiv?: () => void;
};

const SUCSS: SUCESSType = {};

That said, the value of fadeDiv is defined immediately afterwards, so there's no need for the property to be optional (which would require that you test it exists before calling it).

You can just assigned the function when you create the object.

const SUCSS = {
    fadeDiv = function () { /* function body */ }
};
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Near the top of the file, you need to write var fadeDiv = ... instead of fadeDiv = ... so that the variable is actually declared.

The error "Property 'fadeDiv' does not exist on type '{}'." seems to be triggering on a line you haven't posted in your example (there is no access of a fadeDiv property anywhere in that snippet).

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • Sorry about that.. Here is the complete code... just had a namespace left out in the example but the error is the same. The error happens on the SUCSS.fadeDiv(); in the document load and also in the SUCSS.fadeDiv = function(){ line. – jvcoach23 Dec 14 '15 at 19:14
  • It's not much of an improvement because you haven't posted the definition of `SUCSS` either... – Ryan Cavanaugh Dec 14 '15 at 19:21