dimanche 10 janvier 2021

Extracting array of types in typescript

I would like to implement the following functionality(the functions 'PropertyTypes' and 'PropertyNames'):

type A = {
    foo: string;
    bar: number;
}


function getArrayOfTypes<T>(): string[] {
    return PropertyTypes<T>();
}

function getArrayOfProperties<T>(): string[] {
    return PropertyNames<T>();
}

const types: string[] = getArrayOfTypes<A>(); // ["string", "number"]
const names: string[] = getArrayOfProperties<A>(); // ["foo", "bar"]

Now I have seen libraries like "ts-reflection" and such. The problem with them is that they can't supply types at runtime when it's wrapped in another function (a.k.a getArrayOf), meaning it would only work with a direct reference to the type. I'm also open to the possibility such that A is a class an not a type, meaning:

class A {
    constructor(foo: string, bar: number){}
}

function getArrayOfTypes<T>(): string[] {
    return PropertyTypes<T>();
}

function getArrayOfProperties<T>(): string[] {
    return PropertyNames<T>();
}

const types: string[] = getArrayOfTypes<A>(); // ["string", "number"]
const names: string[] = getArrayOfProperties<A>(); // ["foo", "bar"]




Aucun commentaire:

Enregistrer un commentaire