簡體   English   中英

在打字稿中使用reduce,錯誤“元素隱式具有'任何'類型,因為類型的表達式不能用於索引類型'{}'”

[英]use reduce in typescript, Error "element implicitly has an 'any' type because expression of type can't be used to index type '{}'"

我得到錯誤:

元素隱式具有 'any' 類型,因為類型 'POST_TYPE' 的表達式不能用於索引類型 '{}' 屬性 '[POST_TYPE.POST]' 在類型 '{}' 上不存在;

在具有如下接口的函數上使用 reduce 時出錯:

// enum
export const enum POST_TYPE {
  POST = 'POST',
  BOARD = 'BOARD',
  ...
}

// interface
export interface Post {
  postType?: POST_TYPE[];
}

export interface PostType {
  POST?: boolean;
  BOARD?: boolean;
}

// function
const exec = (prevType: Post['postType'], type: PostType) => {
 const prevObject = prevType.reduce((prev, it) => {
    prev[it] = true; -->> ERROR in prev[it]
    return prev;
  }, {});
}

我犯了什么錯誤?

一個問題是您的參數prevType: Post['postType']可能是undefined ,因為Post['postType']可能是undefined 不確定您要在那里做什么,但可能需要在Post上設置postType屬性,並在將對象傳遞給exec之前進行類型檢查。

在代碼中,第二個參數傳遞到reduce缺少一個type -它只是一個普通的對象,你沒有一個類型參數傳遞給.reduce ,所以打字稿不會讓你隨心所欲的鍵值對添加到它。

如果將類型參數傳遞給reduce ,這將表示初始值和累加器的類型。 在這里,因為類型將是一個具有POST_TYPE部分屬性的POST_TYPE ,所以創建這樣一個對象類型並使用Partial 然后你可以斷言返回值是一個完整的對象(沒有缺少屬性):

export interface Post {
    postType: POST_TYPE[];
}
const exec = (prevType: Post['postType']) => {
    type PostObj = {
        [T in POST_TYPE]: boolean;
    };
    const prevObject = prevType.reduce<Partial<PostObj>>((prev, it) => {
        prev[it] = true;
        return prev;
    }, {}) as PostObj;
};

但是, reduce有點冗長,而且在創建單個對象時可能不是正確的工具 僅聲明對象並分配給其屬性可能更合適,或者使用Object.fromEntries

const postObj = Object.fromEntries(
    prevType.map(it => [it, true])
) as PostObj;

(不幸的是,TS 似乎還不能充分推斷fromEntries的返回值的類型,因此需要類型斷言)

暫無
暫無

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

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