我尝试在Node.js / Express项目中使用Typescript,因为我更喜欢严格键入。但是,我是Typescript的新手。
我的目标是使用Firebase和Typescript(而不是Google Cloud函数)保存数据。
我的体系结构如下:
/people/create
的API POST带有JSON {name:“ Guy”} Person
对象,然后将其发送到DatabaseManager
(write_person(person)
)DatabaseManager
从Person对象中创建一个Firebase友好对象并将其发送到FirebaseManager.write(FirebaseReferences.People, data)
FirebaseManager
将此数据保存到Firebase并返回到DatabaseManager
,后者返回到路由器调用。router.post('/person/create', (req: Request, res: Response) => {
var person: Person = new Person(req.json...name);
var uuid: String = DatabaseManager.write_person(person);
res.send(uuid);
});
export module DatabaseManager {
export function write_person(person: Person): String {
return FirebaseManager.write(FirebaseReferences.People, person.to_dict());
}
}
export enum FirebaseReferences {
People = "/people"
}
export module FirebaseManager {
export function write(ref: FirebaseReferences, data: object): String {
try {
var new_ref: firebase.database.Reference = db.ref(ref.toString());
var uuid: String = new_ref.push(data).key;
return uuid;
} catch (error) {
console.log("FirebaseManager, write(): " + error);
throw error;
}
}
}
出现以下错误:
app/database_manager/FirebaseManager.ts:33:17 - error TS2322: Type 'string | null' is not assignable to type 'String'.
Type 'null' is not assignable to type 'String'.
33 var uuid: String = new_ref.push(data).key;
~~~~
[6:29:05 PM] Found 1 error. Watching for file changes.
答案 0 :(得分:2)
DatabaseReference.key
返回一个可为空的类型,如错误消息中的string | null
所示。您分配了一个不可为空的String
,因此编译器可以正确地得出类型不兼容的结论。
您要么需要分配一个可为空的类型,要么将可为空的字符串转换为不可为空的字符串。
var uuid?: string = new_ref.push(data).key;
let key = new_ref.push(data).key;
var uuid: string = key !== null ? key : "";