首页 > 解决方案 > “typeof window”类型上不存在属性“location”

问题描述

我的代码一直在工作,直到我升级了打字稿和反应框架。这个错误发生在 window.location.assign("#/home/dashboard");行上。. 我已阅读文章,但仍然无法解决问题。我也认为 window 属性来自modernizer.js。 目前,我尝试运行该项目时遇到的错误如下:

TS2339:“typeof 窗口”类型上不存在属性“位置”。

这是下面的代码

import RaisedButton from "material-ui/RaisedButton";
import {ActionLockOutline, SocialPerson} from "material-ui/svg-icons";
import * as React from "react";
import {hot} from "react-hot-loader";
import { OAuth } from "../../Shared/Services/OAuth";
import { Component, IComponentState } from "../../Shared/Utilities/Component";
import { Log } from "../../Shared/Utilities/LogUtil";
import { Validation } from "../../Shared/Utilities/Validation";

// import { StorageUtil } from "../../Shared/Utilities/StorageUtil";

interface ILoginState extends IComponentState {
    userName: string;
    password: string;
}

class Form extends Component<any, ILoginState> {

    constructor(props: any) {
        super(props,
            {
                password: "",
                userName: "",
            });

    }

    public loginClick = () => {
        // this.warningNoti("All fields marked red are required");

        if (Validation.formValidation("#loginForm")) {
            OAuth.userLogin(this.state.userName, this.state.password, (loginResponse: any) => {
                Log.consoleObj(loginResponse);

                this.successNoti("User successfully logged in");

                window.location.assign("#/home/dashboard");

            }, (status: string, jqXhr: any) => {
                // console.log(status);
                // console.log(jqXhr);
                this.setState({password: ""});
                this.infoNoti("Incorrect username or password, please check credentials.");
            });
        } else {
            this.warningNoti("All fields marked red are required");
        }

    }
}

标签: javascriptreactjstypescript

解决方案


首先回答您的问题:为什么 tslint 会提出“类型 'window' 上不存在属性 'location'。这是因为 Typescript 定义了一些类型,默认类型和自定义类型。对于 typescript 窗口是自定义类型。默认类型是number、string、boolean、any等。所以当你想使用window时,它被视为一个window对象,它具有assign、location等功能,在默认的lib.dom.d.ts中定义为接口。暂时我建议您通过创建一个类型设置为 any 的 const 来解决此问题。参考:https

://www.typescriptlang.org/docs/handbook/basic-types.html 解决方案/解决方法:由您自己设置常量的类型这样做:

const temp: any = window;
temp.location.assign('#/home/dashboard');

推荐阅读