如何映射定义为FieldValue

对于在Firestore文档的TypeScript界面​​中如何定义数组值,我还有些困惑,同时还利用了FieldValue.arrayUnion()。依赖关系:TypeScript 3.7.2和@ google-cloud / firestore 2.6.0。

即。该界面包括一个“成员”键,该键是一个字符串数组:

import * as firestore from "@google-cloud/firestore";

interface SomeDoc {
  members: string[] | firestore.FieldValue;
}

const foo: SomeDoc = {
  members: ["s"]
};

const bar = foo.members.includes("s") ? "does include" : "does not include";

我可以使用Firestore的FieldValue arrayUnion()和arrayRemove()方法成功更新值,这很棒。但是,TypeScript会引发以下类型错误:

TypeScript error:
Property 'includes' does not exist on type 'string[] | FieldValue'.
  Property 'includes' does not exist on type 'FieldValue'.  TS2339

有人对如何最好地定义这种价值有任何提示吗?

a68434576 回答:如何映射定义为FieldValue

TypeScript允许您指定联合中给定的任何一种类型,但不允许您在没有先使用type guard to differentiate the type的情况下读出这些类型中的任何一种。该部分说:

  

您只能访问保证属于联合体类型的所有组成部分的成员。

因此,按照您的定义,您可以通过这样的防护来满足TS:

const bar = (foo.members as string[]).includes("s") ? "does include" : "does not include";

请注意,如果您保护的不是真正的基础类型,则可能会导致运行时错误。

本文链接:https://www.f2er.com/3127128.html

大家都在问