gpt4 book ai didi

javascript - 将具有强制属性的对象转换为具有相同可选属性的对象

转载 作者:行者123 更新时间:2023-11-29 15:14:03 24 4
gpt4 key购买 nike

我正在思考为什么以下方法不起作用:

/* @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);
^ Cannot cast `a` to `B` because string [1] is incompatible with undefined [2] in property `foo`.
References:
4: foo: string ^ [1]
8: foo?: string ^ [2]

我想做的就是将一个属性保证存在的对象转换为一个属性可能存在的对象——这样不是可以吗?

Try Flow link here (不知道这会工作多久)

最佳答案

因为可以将nullundefined 写入b.foo,所以您可以这样做:

b.foo = null
console.log(a.foo) // null

显然,我们不希望 a.foo 为空,因此 Flow 会警告我们您遇到的错误。为防止此错误(并满足 Flow 的类型检查),您可以将 B 的 foo 属性标记为 read only (也称为“covaiant”)然后赋值工作(我们不会不小心覆盖 foo 属性)。

这里有一些实际的例子:

( Try )

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;

关于javascript - 将具有强制属性的对象转换为具有相同可选属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com