如何在Typescript

时间:2016-04-12 11:32:05

标签: typescript intellisense strong-typing

typescript中使用匿名类型链接功能时,例如:

  let array = [{ seed: 2 }, { seed: 3 }];
  array
    .map(i => ({ seed: i.seed, square: i.seed * i.seed }))
    .forEach(i => console.log(`square for ${i.seed} is ${i.square}`));

我需要为地图功能定义新的匿名类型。如果我有多个步骤都会生成新属性,我最终会编写大量定义代码来获取所有属性。 我可以使用$.extend(或Object.assign),但这样我就会失去智能感和强力打字。

  array
    .map(i => $.extend(i, { square: i.seed * i.seed }))
    .forEach(i => console.log(`square for ${i.seed} is ${i.square}`));

如何在不保留强类型的情况下再次定义所有属性的情况下扩展匿名对象?

2 个答案:

答案 0 :(得分:2)

怎么样:

interface A {
    seed: number;
}

interface B extends A {
    square: number;
}

let array: A[] = [{ seed: 2 }, { seed: 3 }];
array
    .map<B>(a => { 
        return { seed: a.seed, square: a.seed * a.seed } 
    })
    .forEach(b => console.log("square for ${b.seed} is ${b.square}"));

或(如果你想保持匿名):

let array = [{ seed: 2 }, { seed: 3 }];
array
    .map<{seed: number, square: number}>(a => {
        return { seed: a.seed, square: a.seed * a.seed }
    })
    .forEach(b => console.log("square for ${b.seed} is ${b.square}"));

(在playground中使用)

答案 1 :(得分:2)

我终于找到了解决方案。这可以通过Intersection Types来实现。这些可以与匿名类型和类一起使用。在下面的示例中,extend函数将复制每个对象的属性并返回Intersection Type的对象。这将减少大量的类型定义代码,而不会丢失智能感知和强类型。

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];
        }
    }
    return result;
}

let array = [{ seed: 2 }, { seed: 3 }];

array
    .map(i => extend(i, { square: i.seed * i.seed }))
    .map(i => extend(i, { cube: i.square * i.seed }))
    .forEach(i => console.log(`square for ${i.seed} is ${i.square} and cube is ${i.cube}`));

Playground

相同

这是实施的。在core-js及其type definitions返回交叉点类型:

assign<T, U>(target: T, source: U): T & U;