关于联合类型的一些疑问
来源:3-23 高级类型 - 交叉类型

年轻人丶
2020-05-16
function extend<T, U> (first: T, second: U): T & U {
let result = {} as T & U
for (let id in first) {
result[id] = first[id] as any
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result[id] = second[id] as any
}
}
return result
}
first: T, second: U
中的T,U
是代表first,second
本身还是内部所有成员?result[id] = first[id] as any
,这段代码result
接受的是T & U
类型,但为什么first[id]
类型断言为any
, 却可以通过,这是为什么?- 为什么这种写法会报错,
first[id]
改为first[id] as any
就可以通过?
function extend<T, U> (first: T, second: U): T & U {
let result = {} as T & U
for (let id in first) {
result[id] = first[id]
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result[id] = second[id]
}
}
return result
}
写回答
1回答
-
ustbhuangyi
2020-05-17
首先,T 和 U 代表泛型,它跟你实际传入什么类型有关。
其次,first[id] 的类型设置为 any,any 是可以赋值给任何类型的。00
相似问题