Javascript 将具有强制属性的对象强制转换为具有相同可选属性的对象
我正试图弄明白为什么以下方法不起作用:Javascript 将具有强制属性的对象强制转换为具有相同可选属性的对象,javascript,flowtype,Javascript,Flowtype,我正试图弄明白为什么以下方法不起作用: /* @flow */ type A = { foo: string } type B = { foo?: string } const a: A = { foo: 'bar' }; const b: B = (a: B); 流动给了我: 12:const b:b=(a:b); ^无法将'a'强制转换为'B',因为字符串[1]与属性'foo'中未定义的[2]不兼容。 参考资料: 4:foo:string^[1] 8:foo?:字符串^[2]
/* @flow */
type A = {
foo: string
}
type B = {
foo?: string
}
const a: A = { foo: 'bar' };
const b: B = (a: B);
流动给了我:
12:const b:b=(a:b);
^无法将'a'强制转换为'B',因为字符串[1]与属性'foo'中未定义的[2]不兼容。
参考资料:
4:foo:string^[1]
8:foo?:字符串^[2]
我所要做的就是将一个属性保证存在的对象转换成一个属性可能存在的对象-这样可以吗
(不知道这能工作多久)因为可以将
null
或未定义的写入b.foo
,您可以执行以下操作:
b.foo = null
console.log(a.foo) // null
显然,我们不希望a.foo为null,因此Flow会用您遇到的错误警告我们。为了防止此错误(并满足Flow的类型检查),您可以将B的foo
属性标记为(也称为“”),然后分配工作(并且我们不会意外地覆盖foo
属性)
下面是一系列的例子:
()
A型={
foo:string
}
B类={
foo?:字符串
}
常数a:a={foo:'bar'};
//示例1:两者都是只读的
常数b:$ReadOnly=(a:$ReadOnly);
//示例2:仅b只读
常量b_readonly_from_writeable1:$readonly=a
类型A\u只读={
+foo:string//只有foo属性是协变的
}
//Alt表格:
//键入A_ReadOnly=$ReadOnly
//或
//键入A_ReadOnly=$ReadOnly
类型B_只读={
+foo?:字符串
}
//示例3:两个都是只读的at类型声明
常数a\u readonly:a\u readonly=a
常数b_readonly:b_readonly=a_readonly;
//示例4:将可写对象分配给只读对象
const b_readonly_from_writeable2:b_readonly=a;
type A = {
foo: string
}
type B = {
foo?: string
}
const a: A = { foo: 'bar' };
// Example 1: Both readonly
const b: $ReadOnly<B> = (a: $ReadOnly<B>);
// Example 2: Just b readonly
const b_readonly_from_writeable1: $ReadOnly<B> = a
type A_ReadOnly = {
+foo: string // Just the foo property is covariant
}
// Alt forms:
// type A_ReadOnly = $ReadOnly<A>
// or
// type A_ReadOnly = $ReadOnly<{
// foo: string
// }>
type B_ReadOnly = {
+foo?: string
}
// Example 3: both readonly at type declaration
const a_readonly: A_ReadOnly = a
const b_readonly: B_ReadOnly = a_readonly;
// Example 4: assigning a writeable object to a readonly one
const b_readonly_from_writeable2: B_ReadOnly = a;