簡體   English   中英

TypeScript:如何聲明記錄或記錄數組的類型?

[英]TypeScript: How to declare type for Record or Array of Records?

假設有一個apiCall function,它返回一個 promise,它解析為一個 object,它具有一個data屬性(如 Ax RecordRecord數組) 我正在嘗試適當地聲明類型,但出現錯誤。

這是我聲明我的類型的方式:

type ApiResponseType = {
    data: Record<string, any>[] | Record<string, any>;
};

function apiCall(asArr: boolean): Promise<ApiResponseType> {
    const d = {
        foo: 'bar',
    };
    return Promise.resolve({
        data: asArr ? [d] : d,
    });
}

但是當我這樣使用它時:

(async()=>{
    let a: {[key: string]: any} | null = null;
    let b: {[key: string]: any}[] | null = null;
    a = (await apiCall(false)).data;
    b = (await apiCall(true)).data; // Type 'Record<string, any> | Record<string, any>[]' is not assignable to type '{[key: string]: any;}[] | null'. Type 'Record<string, any>' is missing the following properties from type '{[key: string]: any;}[]': length, pop, push, concat, and 26 more.
    console.log({a, b});
})();

我收到以下錯誤:

鍵入'記錄<字符串,任何> | Record<string, any>[]' 不可分配給類型 '{[key: string]: any;}[] | 無效的'。 類型 'Record<string, any>' 缺少來自類型 '{[key: string]: any;}[]' 的以下屬性:length、pop、push、concat 和另外 26 個。

我認為這可能與被視為 Record<string, any> 的數組有關

這是因為:

declare var a: Record<string, any>[]
declare var b: Record<string, any>

a = b // error
b = a // ok

記錄數組可分配給記錄,但反之亦然。

但是讓我們 go 回到你的例子:

type Data = Record<string, any>[] | Record<string, any>;
type Nullable<T> = T | null

type ApiResponseType<T extends Data> = {
    data: T
};

function apiCall(asArr: true): Promise<ApiResponseType<Record<string, any>[]>>
function apiCall(asArr: false): Promise<ApiResponseType<Record<string, any>>>
function apiCall(asArr: boolean) {
    const d = {
        foo: 'bar',
    };
    return Promise.resolve<ApiResponseType<Data>>({
        data: asArr ? [d] : d,
    });
}
type O = ReturnType<typeof apiCall>

(async () => {
    let a: Nullable<Record<string, any>> = null;
    let b: Nullable<Record<string, any>[]> = null;
    a = (await apiCall(false)).data;
    b = (await apiCall(true)).data;

    // without LET bindings
    {
        const a = (await apiCall(false)).data; // Record<string, any>
        const b = (await apiCall(true)).data; //Record<string, any>[]
    }

})();

借助重載,我們可以給編譯器一些提示。

請參閱本節: // without LET bindings

編譯器能夠找出 function 的 ReturnType

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM