我想在 React + TS 前端和 Node + TS 后端之间共享 TS 类或接口(interface)。问题是 TS 类型在编译时被剥离,所以当我想将类实例转换为 JSON 时我不能使用它们。
我想知道是否有任何解决方案可以让我在静态文件中描述我的对象,生成 TS 类,并将该文件用于数据 hydration 和 dehydration 。一些属性是 moment.js
对象和 Decimal.js
对象。我正在寻找一种可以根据静态描述符完成转换的解决方案,我不需要为每个属性手动编写它。
在 HTTP 请求中使用 dehydration 格式,并将其存储在数据库(Firebase Firestore)中,并由前端直接访问以供读取。
最佳答案
我会使用很棒的 io-ts
来解决这个问题图书馆。
The dehydrated format is used in HTTP request plus it's stored in the DB (Firebase Firestore) and accessed directly by the frontend for reading.
一般来说,我会为不同的层假设不同的序列化格式。如果在您的具体情况下可以进行这种简化,那么 👍
I was wondering if there are any solutions with which I could describe my object in a static file
使用 io-ts
,您可以将一组 codec
定义为代表您的域的 TypeScript 值。编解码器既是验证器又是(反)序列化器,因此您可以很好地将类实例序列化为 JSON 字符串,反之亦然(前提是 JSON 已成功验证,然后使用适当的反序列化值实例化类) .
执行此类工作的简化且非常自定义的编解码器如下:
// class definition:
class MyModel {
constructor(readonly value: number) {}
getValue() {
return this.value;
}
}
// codec definition:
import * as t from 'io-ts';
import { JSONFromString } from 'io-ts-types/lib/JSON/JSONFromString';
const MyModelFromString = new t.Type<MyModel, string, unknown>(
'MyModel',
(value): value is MyModel => value instanceof MyModel,
str =>
t.string
.decode(str)
.chain(JSONFromString.decode)
.chain(json => t.type({ value: t.number }).decode(json))
.map(({ value }) => new MyModel(value)),
instance => JSON.stringify({ value: instance.value })
);
// usage:
MyModelFromString.decode('{ "value": 1 }').fold(
errors => {
console.error(errors);
},
inst => {
// inst has type `MyModel` here
console.log(inst.getValue());
}
);
MyModelFromString.encode(new MyModel(2)); // '{ "value": 2 }'
除此之外,您通常还需要注意序列化某种标记,这样您就可以决定要尝试实例化哪个类,只需查看普通序列化的 JSON 字符串即可。
您可能还想看看 io-ts-types
它已经包含许多您可以重复使用的现成的编解码器,例如 DateFromISOString
。
关于node.js - typescript 中数据 hydration/dehydration 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56755316/