简体   繁体   English

打字稿:对象到类

[英]Typescript: Object to class

Lets say I have a class C and an Instance of Object O (from JSON).假设我有一个 C 类和一个 Object O 实例(来自 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?有没有一种方法可以用 o 分配/初始化 C 的实例,它会检查未定义的值以及类型,而无需自己在复制构造函数/函数中执行此操作?

I'd like to get an error or exception if a value is missing/undefined or the type does not match.如果值缺失/未定义或类型不匹配,我想收到错误或异常。

Thanks!谢谢!

You can use Object.assign :您可以使用Object.assign

class C {
    str:string;
    num:number;
}
var o = JSON.parse("{\"num\":123, \"str\":\"abc\"}");
const instance:C = Object.assign(new C(), o);

I landed here wanting to create a class instance from an object literal.我来到这里想从对象文字创建一个类实例。 Object.assign() works but it isn't type safe. Object.assign()有效,但它不是类型安全的。 Of course, if you have JSON source that's expected but I just wanted to instantiate a class with a known state.当然,如果您有预期的 JSON 源,但我只想实例化一个具有已知状态的类。

From the TypeScript docs , a class also acts as a type. 在 TypeScript docs 中,类也充当类型。 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"
});

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. JSON.parse 的问题是编译器不会在编译时检查它返回的内容。 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

Typescript is a type system that runs at compile time, what you are asking is therefore impossible. Typescript 是一个在编译时运行的类型系统,因此您要问的是不可能的。

You could have a look at type guards and maybe use them to provide type inference inside a conditional block of some kind of parse function.您可以查看type guards并可能使用它们在某种parse函数的条件块内提供类型推断。

What you are asking for is a JSON schema validator.您要的是 JSON 模式验证器。 The validation must be ran in runtime.验证必须在运行时运行。 Check https://github.com/epoberezkin/ajv for a complete JSON schema validator or https://www.npmjs.com/package/js-schema for a simpler one.检查https://github.com/epoberezkin/ajv以获得完整的 JSON 模式验证器或https://www.npmjs.com/package/js-schema以获得更简单的验证器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM