简体   繁体   English

Object 字面量只能指定已知属性,并且“PromiseLike”类型中不存在“数据”<t> '</t>

[英]Object literal may only specify known properties, and 'data' does not exist in type 'PromiseLike<T>'

I have a method that makes a request to a server and, based on the URL, it might return completely differently shaped data.我有一个向服务器发出请求的方法,并且基于 URL,它可能会返回完全不同形状的数据。

Before this I was just casting the expected interface into the returned object:在此之前,我只是将预期的接口转换为返回的 object:

    const data = Promise.resolve(makeSignedRequest(requestParameters));
    return data as Promise<AwesomeResponse>;

but today I came across this syntax, where I can tell the method explicitly what kind of data I'm expecting:但今天我遇到了这种语法,我可以明确地告诉方法我期待什么样的数据:

    const data = Promise.resolve(makeSignedRequest<AwesomeResponse>(requestParameters));
    return data;

Now.现在。 the makeSignedRequest may return types like, AwesomeResponse , GreatResponse , AmazingResponse but there is a common thing in all these. makeSignedRequest 可能会返回诸如AwesomeResponseGreatResponseAmazingResponse之类的类型,但所有这些都有一个共同点。 They all share the same structure - the structure of BaseResponse .它们都共享相同的结构 - BaseResponse的结构。

All my responses extend the BaseResponse , so we're cool there.我所有的回复都扩展了BaseResponse ,所以我们很酷。

Having said all that, TypeScript is still complaining about the following code:说了这么多,TypeScript 还在抱怨以下代码:

import https from "https";
export interface BaseResponse {
    meta: {};
    data: Array<{}>;
    error?: {
        statusCode: number | undefined;
        statusMessage: string | undefined;
    };
}

export const makeSignedRequest = <T>(url): Promise<T> => {
    return new Promise((resolve, reject) => {
        // create Request with event listeners
        const req = https.request(url, (res) => {
            res.on("end", () => {
                if (res.statusCode !== 200) {
                    resolve({
                        data: [],
                        meta: {},
                        error: {}
                    });
                }
            });
        });
    });
};

the resolve({data: [], gets heavily underlined by VS Code, because as I mentioned in the title, resolve({data: [],被 VS Code 强调,因为正如我在标题中提到的,

Argument of type '{ data: never[]; meta: {}; error: { statusCode: number | undefined; statusMessage: string | undefined; }; }' is not assignable to parameter of type 'T | PromiseLike<T> | undefined'.
Object literal may only specify known properties, and 'data' does not exist in type 'PromiseLike<T>'.

What am I missing here?我在这里想念什么?

You need a generic constraint :您需要一个通用约束

export const makeSignedRequest = < T extends BaseResponse  > ...

and a type assertion:和类型断言:

      resolve({
        data: [],
        meta: {},
        error: {
          statusCode: res.statusCode,
          statusMessage: res.statusMessage,
        },
      } as T);

This code works for me in VSCode with TS 3.8.3此代码适用于我在 VSCode 中使用 TS 3.8.3

export interface BaseResponse {
    data: [];
    meta: {};
    error?: {
        statusCode: number | undefined;
        statusMessage: string | undefined;
    };
}

function makeSignedRequest<T extends BaseResponse>(): Promise<T> {
    return new Promise((resolve, reject) => {
        // create Request with event listener
        resolve({
            data: [],
            meta: {},
            error: {},
        } as T);
    });
}

You are saying that: your function return a generic type Promise, so resolve only accepts T as parameter.你是说:你的 function 返回一个泛型类型 Promise,所以resolve只接受 T 作为参数。 But {data: [], meta: {}, error: {}} is not T, as T can be anything (string, number...), so it won't compile.但是{data: [], meta: {}, error: {}}不是 T,因为 T 可以是任何东西(字符串、数字...),所以它不会编译。 Your function does not make sense with generic type, it should return Promise<BaseReponse> , that's all.您的 function 对泛型类型没有意义,它应该返回Promise<BaseReponse> ,仅此而已。 Return Promise<T> does not produce any benefit Return Promise<T>不会产生任何好处

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

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