简体   繁体   中英

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.

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.

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

Your code works just fine:

TypeScript Playground

I suspect your test runner (Jest?) is doing something funky. Move the let TestField... inside it('...', () => { /* here */ }) and try again.

By the way, per general convention of JavaScript, your variables and properties should be camel case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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