- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
type ItemNew = { text: string };
type ItemExist = { text: string, id: number };
function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items = [...itemsNew, ...itemsExist];
// const items: ItemNew[]
}
为什么 items
是ItemNew[]
而不是 Array<ItemNew | ItemExist>
?似乎有关宽类型 ( ItemExist
) 的信息完全丢失了。
最佳答案
考虑这个例子:
type ItemNew = { text: string };
type ItemExist = { text: string, id: number };
type Union = ItemNew | ItemExist
declare var union: Union
const elem = union.text // only text property is allowed
因为 text
对于您被允许获得的两种元素都很常见 text
属性(property)。
因为没有人知道var union
包含 id
或不。允许id
prop 在这种情况下将是不健全的(可能导致运行时错误)。
让我们回到你的例子:
type ItemNew = { text: string };
type ItemExist = { text: string, id: number };
function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items = [...itemsNew, ...itemsExist];
}
事实上items
是 Array<ItemNew> | Array<ItemExist>
的并集.应用相同的规则。属性(property)text
是唯一一个安全的属性。
如果你想能够得到id
Proeprty 你可能不会使用这个助手:
type ItemNew = { text: string };
type ItemExist = { text: string, id: number };
// credit goes to https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
T extends any
? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>
function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items: Array<StrictUnion<ItemNew | ItemExist>> = [...itemsNew, ...itemsExist];
items[0].text // ok
items[0].id // number | undefined
}
关于typescript - 从窄类型和宽类型数组推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69100845/
我想在DIV中做竖线 然后我想在垂直线上对 img 进行分层。(图片是我想要的结果) 我的源代码是这样的。 如何对这些元素进行分层??? 最佳答案 您需要做一些数学运算才能在中心调整它。 .ou
出于各种原因,我正在创建一个网站(尚未在线),该网站具有单独的移动页面。我想向“监控”站点添加一些内容,上面写着“如果浏览器宽度小于 X 像素,请查看 *mobilepagename.html 而不是
当尝试使用 jstat 监视 JVM 的性能时,我看到以下几行 - Timestamp PC PU OC **OU** YGC
html Lorem Ipsum... CSS #outer { background: url('mypic.jpg') no-repeat center top; } #i
我正在使用 sun-codemodel 生成代码。我对泛型有疑问。我知道要生成类似的东西 LinkedList, 我需要用 JType jtype = jCodeModel.ref("LinkedLi
考虑一个简单的系统,其中 PS(处理器系统)启用了 AXI3 主设备,连接到 AXI4 互连,该 AXI4 互连连接到可以访问 BRAM 内存的 BRAM Controller 。 AXI 窄突发的含
我在 Windows 上有一个狭窄的 Python 2.7.6 版本。我还有一个包含“窄”( 0xFFFF) Unicode 代码点的字符串。 >>> wide1 = u'\U0002b740' >>
我有一个函数可以验证 JSON 响应以确保它对应于给定的形状。 这是我定义所有可能的 JSON 值的类型——取自 https://github.com/microsoft/TypeScript/iss
我是一名优秀的程序员,十分优秀!