简体   繁体   English

错误TS2339:类型“字符串”上不存在属性“默认”。**

[英]Error TS2339: Property 'Default' does not exist on type 'string'.**

I am new to Angular 2 - My functionality is working fine in fiddle but when I put in the code base I am getting below errors. 我是Angular 2的新手-我的功能在提琴琴中工作正常,但是当我放入代码库时,我遇到了错误。

app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'. app / components / playing-cables / -update.ts(82,12):错误TS2339:类型“ jQuery”上不存在属性“ options”。 app/components/playing-cables/-update.ts(99,21): error TS2339: Property 'Default' does not exist on type 'string'. app / components / playing-cables / -update.ts(99,21):错误TS2339:类型'string'上不存在属性'Default'。

    storedPreferences.Default = {
    dropdown.options = function(data, selectedKey) {
import {Component, ElementRef, Inject, OnInit,ViewChild} from '@angular/core';
import { sportService } from '../../services/sport.service';
import {playesRightBarMultiTabComponent} from '../playing-sports/playes-right-bar-multi-tab'
import {playerComponent} from '../player/player.component';
import {ProgressCircle} from '../shared/progress/progress-circle';
import {playeService} from '../../services/playeService';
import {playingsportsEvergreen} from '../playing-sports/playe-sports-evergreen';
import {TextDecoder} from 'text-encoding-shim';
import { Router} from '@angular/router';
import {NetworkCarousel} from '../shared/content/network-carousel';
import {KendoGridComponent} from '../grid/grid.component';
import { TranslateService } from '../../translate/translate.service';
//import { ProgressCircle } from '../shared/progress/progress-circle';



@Component({
    selector: 'downlinkBulkUpdate',
    templateUrl: "./app/components/playing-cables/downlink-bulk-update.html",
})

export class downlinkBulkUpdate {
    public dataSourceVal;
    public selectedRowsUID = [];
    private count: boolean = true;
    private selectAll: boolean;


    @ViewChild(KendoGridComponent) private gridkendo: KendoGridComponent;

    constructor(public elementRef: ElementRef,private router: Router){
    }

    private kendocommand = {
        edit: { createAt: "bottom" },
        group: false,
        reorder: true,
        resize: true,
        sort: true,
        filter: { mode: "row,menu" },
        autoBind: false,
        pager: { messages: { display: "Showing {0} to {1} of {2} entries" } },
        model: {},
        columns: [],
        pagesize: 50,
        getComponentUrl: "admin/v1/lockedItems",
        saveStatus: false,
        excelfileUidName: "ViewUnlockExport",
        excelFileName: {
            fileName: "ViewUnlockExport",
            allPages: true
        },
        change: function (e) {
            console.log("kendocommand downlink-bulk-update");

            $('tr').find('[type=checkbox]').prop('checked', false);
            $('tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
        },
        searchFields: []
    };

    ngOnInit() {

        $("tr th[data-field='codeLong']").hide();



        if ($('input.checkbox_check').prop('checked')) {
          //blah blah
          alert("checked");

          $("tr th[data-field='codeLong']").show();
        }


        $("#win1").hide();

        /*document.getElementById('cars').options[0].text = localStorage.getItem("someVarName") || 'unkonwn';
        var dropdown = $('<select>');
        alert("I am here dropdownmenu select"); */
            var dropdown = $('#cars');
        dropdown.options = function(data, selectedKey) {
          var self = this;
          var newOptions = '<option value="Default">Default</option>'; //create one objec to save new options
          $.each(data, function(ix, val) {
           var selected = (val == selectedKey) ? 'selected="selected"' : '';
              if (val != 'Default') {
                newOptions += '<option value="' + val + '" ' + selected + '>' + val + '</option>';
             }
            //data.push(option);
          });
          self.html(newOptions);
          self.change();
        }
        //var array = ['one', 'two', 'three'];
        var array = [];
        var storedPreferences = localStorage.getItem('preferences');
        storedPreferences = (storedPreferences) ? JSON.parse(storedPreferences) : {};
        storedPreferences.Default = {
            columns: [0,1,2],
        };
        for (var storedPreference in storedPreferences) {
            array.push(storedPreference);
        }
        dropdown.options(array, 'Default');
        //$('body').append(dropdown);
        $('#btnSubmit').on('click', function(ix, val) {
          //should clear out the current options
          //and replace with the new array
          alert("I am here dropdownmenu");
          var newArray = ['four', 'five', 'six'];
          dropdown.options(newArray, 'Default');
        });



        $("#open1").click(function() {
          alert("I am here");

          $("#win1").show().kendoWindow({
            width: "300px",
            height: "500px",
            modal: true,
            title: "Window 1"
          });
          $("#win1").data("kendoWindow").open();
        });

        $("#clearPrefrence").click(function() {
          alert("clearPrefrence");
          //localStorage.clear();
          //$("#cars option[value=volvo]").remove();
          if ($('#cars').val() != 'Default') {
            var preferences = localStorage.getItem('preferences');
            if (preferences) {
                preferences = JSON.parse(preferences);
            }
            else {
                preferences = {};
            }
              delete preferences[$('#cars').val()];
              localStorage.setItem('preferences', JSON.stringify(preferences));
              $("#cars option:selected").remove();
            $("#cars").change();
          }

        });

        $("#win1Submit").click(function() {

          var testingMickey = $("#mickey").val();
          alert("win1Submit I am here--->" + testingMickey);
          //document.getElementById('cars').options[0].text = testingMickey;

          var someVarName = testingMickey;
          var preferences = localStorage.getItem('preferences');
          if (preferences) {
              preferences = JSON.parse(preferences);
          }
          else {
              preferences = {};
          }
          var preference = {
            columns: [],
          }
          $('#rmenu input[type=checkbox]:checked').each(function() {
              preference.columns.push($(this).data('index'));
          });
          preferences[testingMickey] = preference;
          localStorage.setItem('preferences', JSON.stringify(preferences));
          var getItemsomeVarName1 = localStorage.getItem('preferences');
          getItemsomeVarName1 = JSON.parse(getItemsomeVarName1);
          var optionArray = [];
          for (var key in getItemsomeVarName1) {
              optionArray.push(key);
          }
          alert("getItemsomeVarName1 I am here--->" + getItemsomeVarName1[testingMickey].columns.length);
                dropdown.options(optionArray, testingMickey);
          $("#win1").data("kendoWindow").close();

        });




        setGrid();

         function toggleColumns() {
            $('#rmenu input[type=checkbox]').each(function(index) {
              $(this).data('index', index);
            $(this).attr('data-index', index); 
          });
          $('#rmenu input[type=checkbox]').change(function() {
            var index = $(this).data('index') + 1;
            if ($(this).is(':checked')) {
                $('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').show();
            }
            else {
                $('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').hide();
            }
          });

          $('select').change(function() {
              $('#rmenu input[type=checkbox]').removeAttr('checked').prop('checked', false);
              var preferences = localStorage.getItem('preferences');
            preferences = (preferences) ? JSON.parse(preferences) : {};
            var columns = [0,1,2];
            var key = $(this).val();
            if (preferences && preferences[key]) {
                columns = preferences[key].columns;
            }
            for (var a = 0; a < columns.length; a++) {
                $('#rmenu input[type=checkbox][data-index=' + a + ']').prop('checked', true).attr('checked', 'checked');
            }

            $('#rmenu input[type=checkbox]').each(function() {
                $(this).change();
            });
          });
        }

        toggleColumns();

        $('.k-grid-header').on('contextmenu', function(e) {
          e.preventDefault();
          let menu = document.getElementById("rmenu");
          menu.style.top = e.clientY + 'px';
          menu.style.left = e.clientX + 'px';

          menu.className = "show";
        });

        $(document).bind("click", function(event) {
          document.getElementById("rmenu").className = "hide";
        });



        function setGrid() {

          var ds1 = new kendo.data.DataSource({
            transport: {
              read: {
                //using jsfiddle echo service to simulate JSON endpoint
                url: "/echo/json/",
                dataType: "json",
                type: "POST",
                data: {
                  // /echo/json/ echoes the JSON which you pass as an argument
                  json: JSON.stringify({
                    "country": [{
                        "codeLong": "AUT",
                        "codeShort": "AT",
                        "name": "Austria"
                      },
                      {
                        "codeLong": "BEL",
                        "codeShort": "BE",
                        "name": "Belgium"
                      },
                      {
                        "codeLong": "BGR",
                        "codeShort": "BG",
                        "name": "Bulgaria"
                      }
                    ]
                  })
                }
              }
            },
            schema: {
              data: "country",
              model: {
                fields: {
                  codeLong: {
                    type: "string"
                  },
                  codeShort: {
                    type: "string"
                  },
                  name: {
                    type: "string"
                  }
                }
              }
            }
          });



          $("#grid1").kendoGrid({
            dataSource: ds1,
            height: 180,
            scrollable: {
              virtual: true
            },
            columns: [{
                field: "codeLong",
                title: "codeLong"
              },
              {
                field: "codeShort",
                title: "codeShort"
              },
              {
                field: "name",
                title: "name"
              }

            ]
          });
        }






        alert("downlink-bulk-update");
        console.log("downlink-bulk-update");
        let that = this;

        $(document).ready(function(){
            $(".showHideIcon").click(function(){
                alert("titleSearchResults");
            });
        });

        this.kendocommand.model = {
            id: "isSelected",
            fields: {
                contextRow: { editable: false },
                isSelected: { type: "boolean", editable: true, filterable: false },
                moduleName: { type: "string", editable: false },
                entityId: { type: "string", filterable: true, editable: false, nullable: false },
                entityName: { type: "string", editable: false, nullable: true },
                network: { type: "string", editable: false },
                entityType: { type: "string", editable: false },
                userLocked: { type: "string", editable: false },
                additionalComments: { type: "string", editable: false },
                checkOutDate: { editable: false }

            }
        };
        this.kendocommand.columns = [
            {
                field: 'contextRow',
                width: 25, locked: true
            },
            {
                field: "isSelected", filterable: false, sortable: false, editable: true, title: "Is Selected",
                template: function (container) { return that.checkboxchecker(container, "isSelected") },
                width: 30,
                headerTemplate: '<span class="displayBlock"><input type="checkbox" id="unlockCheck" /></span>'
            },
            {
                field: "moduleName",
                title: "Module Name", filterable: that.gridkendo.getAutoFilterName("contains", "moduleName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function moduleName(options) {
                    console.log("downlink-bulk-update 2");
                    return that.gridTemplate(options, "moduleName", false);
                },
                width: 150
            }, {
                field: "entityId", title: "ID",
                filterable: that.gridkendo.getAutoFilterName("eq", "entityId"),
                headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityId(options) {
                    console.log("ending this.kendocommand.columns");

                    return that.gridTemplate(options, "entityId", false);
                },

                width: 90
            }, {
                field: "entityName", filterable: that.gridkendo.getAutoFilterName("contains", "entityName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityName(options) {
                    return that.gridTemplate(options, "entityName", false);
                },
                title: "Name",
                width: 150
            }, {
                field: "network",
                title: "Network",
                filterable: that.gridkendo.getAutoFilterName("contains", "network"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function networkName(options) {
                    return that.gridTemplate(options, "network", false);
                },

                width: 110
            }, {
                field: "entityType",
                title: "Type", filterable: that.gridkendo.getAutoFilterName("contains", "entityType"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function entityType(options) {
                    return that.gridTemplate(options, "entityType", false);
                },
                width: 150
            }, {
                field: "userLocked",
                title: "User Locked", filterable: that.gridkendo.getAutoFilterName("contains", "userLocked"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function userLocked(options) {
                    return that.gridTemplate(options, "userLocked", false);
                },
                width: 150
            }, {
                field: "additionalComments",
                title: "Additional Comments bulk", filterable: that.gridkendo.getAutoFilterName("contains", "additionalComments"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function additionalComments(options) {
                    return that.gridTemplate(options, "additionalComments", false);
                },
                width: 200
            }, {
                field: "checkOutDate",
                title: "Date Checked Out", filterable: that.gridkendo.getAutoFilterName("contains", "checkOutDate"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
                template: function checkOutDate(options) {
                    return that.gridTemplate(options, "checkOutDate", false);
                },
                width: 200
            }
        ];

        console.log("ending this.kendocommand.columns");
    }

    private gridTemplate(options: any, fieldName: any, mandatory: any) {
        console.log("gridTemplate downlink-bulk-update");

        let value = options[fieldName];
        if (options[fieldName] == null || options[fieldName] == undefined) {
            value = "";
            options[fieldName] = " ";
        }
        options[fieldName + "FilterRowId"] = value;
        return value;
    }

    checkboxchecker(container, fieldName: any): any {
        console.log("checkboxchecker downlink-bulk-update");

        if ((this.selectedRowsUID.indexOf(container.uid) != -1) || this.selectAll) {
            container.isSelected = true;
            return '<input type="checkbox" checked="checked" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';

        } else {
            this.count = true;
            container.isSelected = false;
            return '<input type="checkbox" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
        }
    }

}



‌

I suppose the 'options' problems occurs here: 我想这里出现“选项”问题:

var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) ...

Well, this works in JavaScript, but the error the TypeScript compiler gives you is due to static type-checking. 好的,这在JavaScript中有效,但是TypeScript编译器给您的错误是由于静态类型检查引起的。 dropdown is here a jQuery object, and that type (assuming you're using type definitions for jQuery) does not declare a options property, so assigning to it generates an error. 这里的dropdown是一个jQuery对象,并且该类型(假设您使用的是jQuery的类型定义)没有声明options属性,因此对其进行赋值会产生错误。 To allow TypeScript to do this, you must typecast to any , so the object behaves like any JavaScript object: 要允许TypeScript执行此操作,必须将typecast转换为any ,以便该对象的行为类似于任何JavaScript对象:

var dropdown: any = $('#cars');
dropdown.options = (...)

In the case of .Default it is the same error: you are declaring storedPreferences as .Default的情况下,它是相同的错误:您将storedPreferences声明为

var storedPreferences = localStorage.getItem(...);

TypeScript knows that localStorage.getItem returns a string , so it considers storedPreferences to be of type string. TypeScript知道localStorage.getItem返回一个string ,因此它认为storedPreferences是string类型。 In TypeScript you cannot change the type of a variable. 在TypeScript中,您无法更改变量的类型。 In fact, it's the kind of thing it has been designed to prevent (as it is common in JavaScript and cause of frequent errors). 实际上,这是它旨在防止的事情(这在JavaScript中很常见,并且经常导致错误)。 TypeScript knows that string does not have a Default property and indicates an error. TypeScript知道该string没有Default属性,并指示错误。

To avoid this, again, you must declare storedPreferences to be of type any : 为了避免这种情况,同样,你必须声明storedPreferences为类型的any

let storedPreferences: any = localStorage.getItem(...);

The problem is that you're programming in TypeScript as if it were JavaScript, and that's why you're getting compiler errors. 问题在于您像使用JavaScript一样在TypeScript中进行编程,这就是为什么会出现编译器错误的原因。 In TypeScript you cannot add new properties to an object of a known type. 在TypeScript中,不能将新属性添加到已知类型的对象。 To do this, you must previously declare the object as any , so TypeScript behaves exactly like JavaScript (though this way you lose TypeScript advantages). 为此,您必须事先将对象声明为any ,以便TypeScript的行为与JavaScript完全相同(尽管这样会失去TypeScript的优势)。

Besides all this, you should avoid using var and use let or const instead. 除此之外,您应避免使用var而应使用letconst

The code in jsfiddle works, because that is JavaScript code, not TypeScript code. jsfiddle中的代码有效,因为那是JavaScript代码,而不是TypeScript代码。

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

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