OiO.lk Blog javascript Typescript – Is it possible to extract a list of types from a constant object?
javascript

Typescript – Is it possible to extract a list of types from a constant object?


I’m trying to read from a data file where everything is stored in arrays, and transfer that to the equivalent Javascript object.

What I want to be able to do with typescript is create a system that automatically reads the arrays, and stores them in corresponding object, but also is able to verify that the types are correct in order to avoid hard to debug errors.

What I’d like to be able to do is something like the following


//Template that will specify types of Typescript, but also allow me to use the keys with javascript
const SaveDataTemplate = {
    id: Number(),
    name: String(),
    someBool: Boolean(),
}

//Type to allow for type-checking the save data input/output
type tSaveData = GetKeyTypesFrom<SaveDataTemplate>; //Theoretically would return constant array type of [number, string, boolean];

//Takes in array from save data and returns key/value object
function fromSaveData(data: tSaveData): typeof SaveDataTemplate {
    const returnObj = {};
    let idx = 0;
    
    for (const key in SaveDataTemplate){
        returnObj[key] = data[idx++];
    }
    
    return returnObj as any;
}

//Takes in object which contains keys which are in SaveDataTemplate and returns array in specific format
function toSaveData(data: typeof SaveDataTemplate): tSaveData {
    const returnArr = [];
    
    for (const key in data){
        returnArr.push(data[key]);
    }
    
    return returnArr as any;
}

In a language like C++ Structs would make this easy, but since Jvascript doesn’t have those it’s turning out to be pretty difficult to find a workaround.



You need to sign in to view this answers

Exit mobile version