typescript 错误TS2532:检查对象是否已定义后,对象可能为“undefined”[重复]

sr4lhrrt  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(252)

此问题已在此处有答案

Can't narrow the type of an object property even after checking it with a type guard(3个答案)
The typescript shows an error "Object is possibly 'undefined'"(1个答案)
5天前关闭。
下面是一个创建hash的helper类的代码:

export default class PageUtil {
    private size: number;
    private step: PageUtilStep;
    private cursor: unknown[] | undefined;

    public constructor(size: number, step: PageUtilStep, cursor?: unknown[]) {
        this.size = size;
        this.step = step;
        this.cursor = cursor;
    }

    public createHash(): string {
        const json = JSON.stringify([this.size, this.step, this.cursor]);

        return createHash("sha1").update(json).digest("hex");
    }
}

type PageUtilStep = "backward" | "forward";

下面是在返回行上获取typescript错误的代码:

export default class TattooLoader {
    private artistCache: Record<string, DataLoader<number, TattooEntity[]>>;

    public constructor() {
        this.artistCache = {};
    }

    public async fillArtist(artist: number, pageUtil: PageUtil): Promise<TattooEntity[]> {
        const hash = pageUtil.createHash();

        if (!this.artistCache[hash]) {
            this.artistCache[hash] = new DataLoader(async (artists) => this.batchArtists(artists, pageUtil));
        }

        return this.artistCache[hash].load(artist);
    }

    private async batchArtists(artists: readonly number[], pageUtil: PageUtil): Promise<TattooEntity[][]> {
        ...
    }
}

我不明白,因为一个得到这个错误后,以测试如果this.artistCache[hash]undefined,并创建它,如果是。
如果我将代码更改为更具体地测试它是否未定义,我会得到相同的错误:

public async fillArtist(artist: number, pageUtil: PageUtil): Promise<TattooEntity[]> {
        const hash = pageUtil.createHash();

        if (this.artistCache[hash]) {
            return this.artistCache[hash].load(artist);
        }

        this.artistCache[hash] = new DataLoader(async (artists) => this.batchArtists(artists, pageUtil));

        return this.artistCache[hash].load(artist);
    }
insrf1ej

insrf1ej1#

索引访问不会缩小undefined的范围。
你需要创建一个中间变量:

const loader = this.artistCache[hash]

if(loader) {
  ...
}

相关问题