Consider a scenario where I have a query class and an execute method structured as follows:
class Query {
name: string;
sql: string;
}
function execute(query: Query): any{
let retVal = {};
retVal[query.name] = true;
return retVal;
}
q = new Query();
q.name = "thisIsMyQueryName";
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// the typeof result is still 'any', but ideally, it should be:
// {thisIsMyQueryName: boolean}
In this case, the object being returned holds a shape that mirrors the instance of the class passed into it. Since the query's "name" can vary at runtime, there is no way to inform the compiler about the presence of a property called "thisIsMyQueryName" in the returned object.
However, I've been exploring methods to enhance static analysis. Although we have multiple query objects with known names during instantiation, achieving full static analysis seems challenging. Experimenting with different approaches involving key of
has shown some potential, but a satisfactory solution remains elusive.
It would be ideal if something like this were possible:
let q = {
sql: "",
queryName: {
thisIsMyQueryName: ""
}
}
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// typeof result == {thisIsMyQueryName: boolean}
While I understand the impossibility of the above code snippet, I believe there must be a way to describe these instances so that the compiler recognizes the presence of a property named keyof q.queryName
.
Any suggestions or insights?