如何获得从类实例克隆的对象的类型? [英] How do you get the type of the object that is cloned from a Class Instance?

查看:138
本文介绍了如何获得从类实例克隆的对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个示例类,但实际上它具有更多的属性

assume I have this example class, but in reality it has many more properties

class Foo {
  name: string
  dob: number

  constructor(name: string, dob: number) {
    this.name = name;
    this.dob = dob;
  }

  get age() {
     return new Date().getTime() - this.dob
  }
}

现在Typescript很聪明,当我实例化该类时,它将为我提供所有正确的属性:

Now Typescript is smart and when I instantiate the class it will give me all the right properties:

var classInstance = new Foo('name', new Date().getTime())

classInstance.name // ok
classInstance.dob // ok
classInstance.age // ok

在我的代码中的某个地方,该类是使用Spread运算符克隆的,我不确定TS在幕后做了什么,但它确实很聪明,并且为我提供了所有正确的属性

Somewhere in my code the class gets cloned using the Spread Operator, I'm not sure what TS does behind the scene but it is really smart and gives me all the right properties

var classJSON = {...classInstance};

classJSON.name // ok
classJSON.dob // ok
classJSON.age // missing

tsplayground

这很棒,但是我有时需要使用classJSON的类型.我想提取它的唯一方法是执行以下操作:

This is great, however I sometime need to use the type of classJSON .. The only way I can think to extract it is to do this:

var classJSON  = {...new Foo('', 0)}
type ClassJSONType = typeof classJSON; 

是否有一种方法可以直接从Foo中提取类型而不需要使用Javascript进行实例化?

Is there a way to extract the type straight out of Foo without needing Javascript to instantiate?

推荐答案

免责声明:这篇帖子是基于 Matt McCutchen的回答.这是一个可靠的解决方案,没有任何JS运行时效果的纯TS.

Disclaimer: this post is a mod based on Matt McCutchen's answer. It's a solid solution, pure TS without any JS runtime effect.

type IfEquals<X, Y, T> =
    (<T>() => T extends X ? 1 : 2) extends
  (<T>() => T extends Y ? 1 : 2) ? T : never;

type JSONify<T> = Pick<T, {
  [P in keyof T]: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
}[keyof T]>;


以上技巧排除了所有readonly字段.要进一步排除方法,请使用以下命令:


Above trick excludes all readonly fields. To further exclude methods, use the following:

type JSONify<T> = Pick<T, {
  [P in keyof T]: IfEquals<{ [Q in P]: T[P] extends Function ? never : T[P] }, { -readonly [Q in P]: T[P] }, P>
}[keyof T]>;

游乐场

这篇关于如何获得从类实例克隆的对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆