Closed
Description
The code comes from the website(http://www.typescriptlang.org/docs/handbook/advanced-types.html) :
function extend<T, U>(first: T, second: U): T & U {
let result = <T & U>{};
for (let id in first) {
(<any>result)[id] = (<any>first)[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
result)[id] = second[id];
}
}
return result;
}
modify the code slightly:
function extend<T, U>(first: T, second: U): T & U {
let result = <T & U>{};
for (let id in first) {
result[id] = first[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
(<any>result)[id] = (<any>second)[id];
}
}
return result;
}
Just remove the type assertion for result and first in the fourth line。
I thought that the code above will be correct,because result is defined as T & U which is considered a type containing both properties from T and U, so that accessing result[keyof T] is valid, since keyof T is assignable to keyof (T & U)。
Metadata
Metadata
Assignees
Labels
No labels