Search code examples
typescripttypescript-genericsstrong-typing

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?

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