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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34274487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:51:13  来源:igfitidea点击:

property does not exists on type '{}'

typescript

提问by jvcoach23

I am using Visual Studio 2013 fully patched. I have a website that i've just created and 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

我正在使用完全修补的 Visual Studio 2013。我有一个刚刚创建的网站,正在尝试使用 jquery、jqueryui 和 jsrender。我也在尝试使用 TypeScript。在 ts 文件中,我收到如下错误

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

类型“{}”上不存在属性“fadeDiv”。

I have the correct references i think for jquery, jqueryui and jsrender for typescript.. but from what I've read this is looking like a d.ts issue. Was hoping someone could help me out.

我有正确的参考,我认为 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. Both times fadeDiv is mention in the javascript there is a red line under it and both errors say the same thing as above.

javascript 中没有错误,但我不想让 Visual Studio 说有错误,如果我能帮忙的话。javascript 中两次都提到了fadeDiv,它下面有一条红线,两个错误都说与上面相同。

thanks shannon

谢谢香农

/// <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 the namespace.. In typescript it appears I would have wanted to do something like this.

对于那些稍后可能会阅读本文的人.. SUCSS 命名空间.. 在打字稿中,我似乎想做这样的事情。

$(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 the page loading by calling it out in with the SUCSS.fadeDiv(); hope that can be helpful.

因此该函数通过使用导出公开,我可以调用 SUCSS.fadeDiv 在页面加载上运行,方法是使用 SUCSS.fadeDiv() 调用它;希望能有所帮助。

回答by 21st

Simply assign the any type to the object:

只需将 any 类型分配给对象:

let bar = <any>{};
bar.foo = "foobar"; 

回答by Luca C.

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

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

回答by Amr Ibrahim

let propertyName= data['propertyName'];

回答by Fenton

When you write the following line of code in TypeScript:

当您在 TypeScript 中编写以下代码行时:

var SUCSS = {};

The type of SUCSSis inferred from the assignment (i.e. 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 fadeDivon the SUCSSobject (this kind of warning often helps you to catch a typo).

并且编译器会警告您对象fadeDiv上没有命名的SUCSS属性(这种警告通常可以帮助您发现拼写错误)。

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');
    }
};

回答by Kovács Botond

I suggest the following change

我建议进行以下更改

let propertyName =  {} as any;

回答by Nils Coussement

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;
      }

回答by Ryan Cavanaugh

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 fadeDivproperty anywhere in that snippet).

错误“ Property 'fadeDiv' does not exist on type '{}'.”似乎是在您未在示例中发布的行上触发的(fadeDiv在该代码段中的任何地方都无法访问属性)。