简体   繁体   English

如何使用泛型在Typescript中获取数据类型

[英]How to get the data type in Typescript using Generics

I have a data structure that is built using generics. 我有一个使用泛型构建的数据结构。 When I go to populate data though, I want to ensure I can convert some simple formats into the proper types. 但是,当我要填充数据时,我想确保可以将一些简单的格式转换为正确的类型。 As the class us configured using Generics, I cannot seem to detect the type of the data in other code. 正如我们使用泛型配置的类一样,我似乎无法检测到其他代码中的数据类型。

This is a simple example extracted from my code: 这是从我的代码中提取的一个简单示例:

export class Field<T> {
    private Name_: string;
    private Value_: T;

    constructor(FieldName:string, Data?:T) {
        this.Name_ = FieldName;
        if( Data !== undefined) {
            this.Value_ = Data;
        }
    }

    /**
     * Get the data value from this class
     * @returns T The value from Value_
     */
    get Value(): T {
        return this.Value_;
    }

    get Type(): string {
        return typeof this.Value_;
    }

    /**
     * Set the data into the data value
     * @param Data T Generic Data member as the raw data to be stored in the field.
     */
    set Value(Data:T) {
        this.Value_ = Data;
    }
}

This is a simple code snippet to demonstrate the problem. 这是演示该问题的简单代码段。 My structure (Field) is defined with a generic (Field) and I expect the value in the data to be of that type. 我的结构(Field)是用通用(Field)定义的,我希望数据中的值属于该类型。

I am trying to test this but I cannot get the type from the Object (as it is of type Field), so I was trying to get the type of the internal data field. 我正在尝试对此进行测试,但无法从对象中获取类型(因为它是字段类型),因此我试图获取内部数据字段的类型。

    describe('Get Type of Value', () => {
        let TestField:Field<number> = new Field<number>('Age', 32);
        it('should return the value type from the definition', () => {
            expect(TestField.Type).toBe('number');
        });
    });

The test fails indicating that the Type getter function returns undefined. 测试失败,表明Type getter函数返回undefined。

 FAIL  
    Expected value to be (using Object.is):
      "number"
    Received:
      "undefined"

Your code works just fine: 您的代码可以正常工作:

TypeScript Playground TypeScript游乐场

I suspect your test runner (Jest?) is doing something funky. 我怀疑您的测试跑步者(开玩笑?)做得有些时髦。 Move the let TestField... inside it('...', () => { /* here */ }) and try again. let TestField... it('...', () => { /* here */ })然后重试。

By the way, per general convention of JavaScript, your variables and properties should be camel case 顺便说一句,按照JavaScript的一般约定,您的变量和属性应为驼峰式

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

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