Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: How to initilize keyof T (generic) at runtime

so I have this TypeScript class where I have a generic and a property of type keyof generic, like this:

export class ColumnDefinition<T> {
    field: keyof T
}

Compiler complains because it needs a default value which I don’t have at compile time, but I don’t want to allow the user to use null or undefined in this property, so I can’t do it like:

export class ColumnDefinition<T> {
    // can't do this, I need to make the field mandatory
    field: keyof T | undefined;
}

my question is, is there a way to somehow initialize the field with a default value at runtime without knowing the generic at compile time? like set whatever first key is in the generic class?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: I don’t want to disable the ts-ignore, I’m looking for a real solution

>Solution :

If you set field with a visibility modifier (public, private, protected) in the constructor then it becomes a class property which is set when you pass in a value when the class is created

export class ColumnDefinition<T> {
    constructor(private field: keyof T){ }

    logField(){
        console.log(this.field);
    }
}

const colDef = new ColumnDefinition<{ x: number; }>('x');

colDef.logField(); //"x"

const badColDef = new ColumnDefinition<{ x: number; }>('foo'); //Error!

See it in action on the TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading