Typescript 如何映射定义为FieldValue的Firestore数组值

Typescript 如何映射定义为FieldValue的Firestore数组值,typescript,google-cloud-firestore,Typescript,Google Cloud Firestore,对于如何在Firestore文档的TypeScript接口中定义数组值,同时利用FieldValue.ArrayNion()的优势,我有点困惑。依赖项:TypeScript 3.7.2和@google cloud/firestore 2.6.0 即,该接口包括一个“members”键,该键是一个字符串数组: import * as firestore from "@google-cloud/firestore"; interface SomeDoc { members: string[]

对于如何在Firestore文档的TypeScript接口中定义数组值,同时利用FieldValue.ArrayNion()的优势,我有点困惑。依赖项:TypeScript 3.7.2和@google cloud/firestore 2.6.0

即,该接口包括一个“members”键,该键是一个字符串数组:

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

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

TypeScript允许您指定联合中给定的任何一种类型,但它不允许您在不使用。该节说:

只能访问保证在联合类型的所有组成部分中的成员

因此,根据您的定义,您可以通过如下方式保护TS:

const bar = (foo.members as string[]).includes("s") ? "does include" : "does not include";
请注意,如果您保护的内容不是实际的底层类型,则这可能会导致运行时错误