Javascript 如何描述可以正确序列化的值?
我有一个函数,它只有在传递的对象可以序列化时才能正常工作,换句话说,如果它不包含符号和函数:Javascript 如何描述可以正确序列化的值?,javascript,typescript,Javascript,Typescript,我有一个函数,它只有在传递的对象可以序列化时才能正常工作,换句话说,如果它不包含符号和函数: createHash("test"); // Will work createHash({ test: "test", method() { } }); // Will not work, throw type error function createHash<T>(data: Serializable<T>): Hash<T> { const sal
createHash("test"); // Will work
createHash({ test: "test", method() { } }); // Will not work, throw type error
function createHash<T>(data: Serializable<T>): Hash<T> {
const salt = createSalt();
return { salt, hash: CryptoJS.PBKDF2(JSON.stringify(data), salt).toString(), };
}
因此,我的问题是:我如何键入Serializable,使其能够生成有用的错误消息并在不手动指定T的情况下工作?关于这一点的讨论从2015年开始,一直在进行中,从2015年开始,一直在进行中
type Serializable<T> =
T extends (Function | symbol) ? never :
T extends (string | number | boolean) ? T :
{ [K in keyof T]: Serializable<T[K]> };
Argument of type 'Serializable<T>' is not assignable to parameter of type 'T'.
'Serializable<T>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
createHash({ test: "test", method() { } }); // Type "() => void is not assignable to type never"