相关疑难解决方法(0)

如何将JSON对象强制转换为typescript类

我从远程REST服务器读取了一个JSON对象.此JSON对象具有typescript类的所有属性(按设计).如何将收到的JSON对象强制转换为类型var?

我不想填充一个typescript var(即有一个带有这个JSON对象的构造函数).它很大并且通过属性按子对象和属性跨子对象复制所有内容将花费大量时间.

更新:您可以将其转换为打字稿界面!

json typescript

348
推荐指数
14
解决办法
38万
查看次数

TypeScript中的构造函数重载

有没有人在TypeScript中完成构造函数重载.在语言规范的第64页(v 0.8)中,有一些语句描述构造函数重载,但没有给出任何示例代码.

我现在正在尝试一个非常基本的课堂宣言; 看起来像这样,

interface IBox {    
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj: IBox) {    
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }   

    constructor() {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

当使用tsc BoxSample.ts运行时,它会抛出一个重复的构造函数定义 - 这很明显.任何帮助表示赞赏.

constructor overloading typescript

344
推荐指数
9
解决办法
20万
查看次数

带有扩展运算符的 Typescript 构造函数

如果与扩展运算符一起使用,则需要将属性分配给从接口定义的唯一属性。

我期待使用带有扩展运算符的打字稿构造函数的解决方案。

例如。

export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: IBrand) {
        this.id = data.id;
        this.name = data.name;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一种选择,所以当我像这样调用这个类时,不知道有多少成员,但我只id, name需要最终对象。

new Brand({...data })
Run Code Online (Sandbox Code Playgroud)

案例:但是当我有 25 个以上的键时 data

export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: Partial<IBrand>) {
        Object.assign(this, data);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不希望再次编写所有属性的构造函数。不管它有 25 个,它只是分配现有的属性将被分配。如果数据具有section, genre或任何其他属性,它将被忽略。

我的第二个片段不起作用。

typescript

3
推荐指数
2
解决办法
3984
查看次数

标签 统计

typescript ×3

constructor ×1

json ×1

overloading ×1