对于如何在TypeScript接口中为Firestore文档定义数组值,同时也利用了FieldValue.arrayUnion(),我有些犹豫。依赖关系: TypeScript 3.7.2和@google/Firesto2.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有人对如何最好地定义这种价值有任何提示吗?
发布于 2019-11-11 04:13:32
TypeScript允许您指定联合中给定的任何类型,但它不允许您在不首先使用类型保护以区分类型的情况下读取其中一种类型。这一节说:
您只能访问保证属于工会类型的所有成员的成员。
因此,根据您的定义,您可以通过这样的保护来满足TS:
const bar = (foo.members as string[]).includes("s") ? "does include" : "does not include";请注意,如果您保护的不是实际的基础类型,这可能会导致运行时错误。
https://stackoverflow.com/questions/58794042
复制相似问题