简体   繁体   English

TypeScript:类型“{}”上不存在属性

[英]TypeScript: Property does not exist on type '{}'

I am using Visual Studio 2013 fully patched.我正在使用完全修补的 Visual Studio 2013。 I am trying to use JQuery, JQueryUI and JSRender.我正在尝试使用 JQuery、JQueryUI 和 JSRender。 I am also trying to use TypeScript.我也在尝试使用 TypeScript。 In the ts file I'm getting an error as follows:在 ts 文件中,我收到如下错误:

Property 'fadeDiv' does not exist on type '{}'.类型“{}”上不存在属性“fadeDiv”。

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.我认为我对 TypeScript 的 JQuery、JQueryUI 和 JSRender 有正确的参考,但从我读过的内容来看,这看起来像是一个 d.ts 问题。

There are no errors in JavaScript, but I don't want to have Visual Studio saying there are errors if I can help it. JavaScript 中没有错误,但如果我能帮上忙,我不想让 Visual Studio 说有错误。 Both times fadeDiv is mentioned in the JavaScript there is a red line under it and both errors say the same thing as above.两次在 JavaScript 中都提到了fadeDiv ,它下面有一条红线,两个错误都说与上面相同。

/// <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.对于稍后可能会阅读本文的人,SUCSS 是命名空间。 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();因此该函数通过使用导出公开,我可以调用SUCSS.fadeDiv以通过使用SUCSS.fadeDiv();调用它来在页面加载时运行SUCSS.fadeDiv(); . . I hope that will be helpful.我希望这会有所帮助。

You can assign the any type to the object:您可以将any类型分配给对象:

let bar: any = {};
bar.foo = "foobar"; 

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注意:这比避免仅对单个字段访问进行类型检查更危险,因为对所有字段的所有连续访问都是无类型的

let propertyName= data['propertyName'];

When you write the following line of code in TypeScript:当您在 TypeScript 中编写以下代码行时:

var SUCSS = {};

The type of SUCSS is inferred from the assignment (ie it is an empty object type). SUCSS的类型是从赋值中推断出来的(即它是一个空对象类型)。

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).并且编译器会警告您SUCSS对象上没有名为fadeDiv的属性(这种警告通常可以帮助您发现拼写错误)。

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):您可以...通过指定SUCSS的类型来修复它(尽管这会阻止您分配{} ,它不满足您想要的类型):

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

Or by assigning the full value in the first place and let TypeScript infer the types:或者首先分配完整的值并让 TypeScript 推断类型:

var SUCSS = {
    fadeDiv: function () {
        // Simplified version
        alert('Called my func');
    }
};

我建议进行以下更改

let propertyName =  {} as any;
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;
      }

Near the top of the file, you need to write var fadeDiv = ... instead of fadeDiv = ... so that the variable is actually declared.在文件顶部附近,您需要编写var fadeDiv = ...而不是fadeDiv = ...以便实际声明变量。

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).错误“ Property 'fadeDiv' does not exist on type '{}'. ”似乎是在您未在示例中发布的行上触发(在该代码段中的任何位置都无法访问fadeDiv属性)。

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 https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype

type Foo = {
  bar: string;
}

const foo: Partial<Foo> = {}
foo.bar = "foobar"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM