Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Object to class

Lets say I have a class C and an Instance of Object O (from JSON).

class C {
  str:string;
  num:number;
}

var o = JSON.parse ("{\"num\":123, \"str\":\"abc\"}");

Is there a way I can assign/initialize an instance of C with o and it checks for undefined values as well as for the type WITHOUT doing it by myself in a copy-constructor/function?

I'd like to get an error or exception if a value is missing/undefined or the type does not match.

Thanks!

like image 579
chris01 Avatar asked Sep 30 '17 09:09

chris01


People also ask

How do you convert a object to a class type in TypeScript?

1) Add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $. extend( this, jsonData) . $.

Does TypeScript have inheritance?

TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript.


3 Answers

You can use Object.assign:

class C {
    str:string;
    num:number;
}
var o = JSON.parse("{\"num\":123, \"str\":\"abc\"}");
const instance:C = Object.assign(new C(), o);
like image 198
Patrick Avatar answered Oct 16 '22 20:10

Patrick


I landed here wanting to create a class instance from an object literal. Object.assign() works but it isn't type safe. Of course, if you have JSON source that's expected but I just wanted to instantiate a class with a known state.

From the TypeScript docs, a class also acts as a type. Thus, the following will work:

class C {
    str: string;
    num: number;

    constructor(source: Partial<C>) {
        Object.assign(this, source);
    }
}

// Ok - all properties
const c1 = new C({
    num: 123,
    str: "abc"
});

// Ok - only some of the properties
const c1 = new C({
    num: 123,
});

// Error: unknown property `unexpectedPropertyName`
const c2 = new C({
    num: 123,
    unexpectedPropertyName: "abc"
});
like image 6
zupa Avatar answered Oct 16 '22 21:10

zupa


Here is an example of creating objects directly, which will give you live error checking. The problem with JSON.parse it that the compiler will not check at compile time what it returns. If you work with unknown live data you will have to write some error check manually.

interface Obj {
  str: string
  num: number
}

class C {
  constructor(o:Obj) { 

  }
}

var o = {test:43, str:"abc"}
var p = {num:43, str:"abc"}

var instanceOne = new C(o) // not allowed
var instanceTwo = new C(p) // allowed
like image 2
Kokodoko Avatar answered Oct 16 '22 19:10

Kokodoko