Avoid unnecessary any casts in advanced types. PR847

This commit is contained in:
zhongsp 2019-03-24 09:55:46 +08:00
parent 772b4953c1
commit 0ed231480c

View File

@ -10,33 +10,37 @@
下面是如何创建混入的一个简单例子("target": "es5")
```ts
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)) {
(<any>result)[id] = (<any>second)[id];
function extend<First, Second>(first: First, second: Second): First & Second {
const result: Partial<First & Second> = {};
for (const prop in first) {
if (first.hasOwnProperty(prop)) {
(<First>result)[prop] = first[prop];
}
}
return result;
for (const prop in second) {
if (second.hasOwnProperty(prop)) {
(<Second>result)[prop] = second[prop];
}
}
return <First & Second>result;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(): void;
log(name: string): void;
}
class ConsoleLogger implements Loggable {
log() {
// ...
log(name) {
console.log(`Hello, I'm ${name}.`);
}
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
var n = jim.name;
jim.log();
const jim = extend(new Person('Jim'), ConsoleLogger.prototype);
jim.log(jim.name);
```
# 联合类型Union Types