【问题标题】:Got TS 2739 error while returning value from promise. Type 'Promise<any>' is missing the following properties from type从 promise 返回值时出现 TS 2739 错误。类型“Promise<any>”缺少类型中的以下属性
【发布时间】:2020-09-12 19:14:58
【问题描述】:

目前我正在编写请求登录服务器的代码并接收它的会话数据并发送到全局上下文。

基本原理是 1)请求并获取 Promise 2)验证获取结果本身和响应状态。 3)为外部元件提供价值。我正在研究 1) 和 2)。

但是在将结果数据返回给外部组件的代码中,我收到了关于数据输入 Type 'Promise&lt;any&gt;' is missing the following properties from type 'SessionInfo': userEmail, userName, sessionToken, duets(2739) 的错误。尽管有严格的数据类型(也许我认为),但我不确定 linter 为什么说 Promise 而不是 Promise>。我认为 TS 未能断言它的类型。

当我使用 Javascript(不输入)运行非常相似的代码时,它在过去可以工作。我不确定为什么会发生这种情况,也不知道出了什么问题。你能检查我的代码吗?

代码如下,有4个文件——用户相关的接口定义文件、处理响应json的接口定义、实际请求获取、响应验证和评估。

当我在return res.dataactionHandler.ts 检查 linting 时,linter 成功预测它的类型。正如 linter 所说,res.dataResponseSet&lt;SessionInfo&gt;.data?: userTypes.SessionInfo

userTypes.ts


export interface SessionInfo {
    userEmail: string,
    userName: string,
    sessionToken: string,
    due: number,
}

commonTypes.ts

export interface ResponseSet<T> { // Response wrapper when it returns with code 200
    statusCode: ResponseStatusCode, // ResponseStatusCode is custom typed status code not for request it self.
    data?: T,
    description?: string,
};

userReq.ts

const login = async (email: string, password: string): Promise<commonTypes.ResponseSet<userTypes.SessionInfo>> => {
    try {
        const request: Request = new Request(
            composeUri(`user/login`, { email, password }),
            {
                method: 'GET',
                headers: { 'Content-type': 'application/json' },
                mode: 'cors',
            }
        );

        const response: Response = await fetch(request);
        if (response.status != 200) throw response.status;

        return await response.json();

    } catch {
        return {
            statusCode: 1,
        };
    }
}

actionHandler.ts

export const doLogin = (email: string, password: string): userTypes.SessionInfo => {
    const result: userTypes.SessionInfo = userReq.login(email, password)
        .then(res => {
            if (res.statusCode != 0) throw new Error(res.description || 'UnknownError');
            return res.data;
        })
        .catch(err => {
            return null;
        });
    return result;
}

我遇到错误的地方是const result:...。我得到了Type 'Promise&lt;any&gt;' is missing the following properties from type 'SessionInfo': userEmail, userName, sessionToken, due ts(2739)。尽管我的代码有严格的类型定义,但我不确定为什么它被识别为“Promise”。

【问题讨论】:

    标签: node.js typescript promise


    【解决方案1】:

    问题在于result 不是SessionInfo。这是一个承诺。

    const result: Promisse<userTypes.SessionInfo | null>;
    

    doLogin由于使用了promise而异步,你应该在里面跟着asyncawait它不能返回userTypes.SessionInfo,结果将是一个promise。

    export const doLogin = async (email: string, password: string): Promise<userTypes.SessionInfo | null> => {
      try {
        const result: commonTypes.ResponseSet<userTypes.SessionInfo> = await userReq.login(email, password);
        if (res.statusCode != 0) throw new Error(res.description || 'UnknownError');
      } catch (e) {
        return null;
      }
      return res.data;
    }
    
    // somewhere in the code (async env)
    await doLogin(email, password);
    

    【讨论】:

    • 我没有给出任何回复描述,抱歉。结果 json 带有 ResponseSet dtype。这意味着{statusCode: number, data: SessionInfo,, description: string} 所以不必在返回结构中使用 response.json。还有一个,据我所知,response.json() 返回 Promise,不等待可以吗?
    • 啊,我明白你的意思了。你可以尝试像上面那样处理它吗?
    • 我现在试试,我才看到这个答案。谢谢
    • 是的,刚刚将其更新为与您的代码中的类型相同。
    • 好的,现在我遇到了真正的问题。 result 是一个承诺,你需要在 doLogin 内部工作,就像使用承诺一样。
    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2022-11-21
    • 2020-12-31
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多