Imagine I have a variable with a name and a value, both of which I need for a specific task such as logging. This can be achieved in the following way:
const some_variable = "abcdef"
const another_variable = 12345
const log1 = (name: string, value: any) => console.log(name, value)
log1("some_variable", some_variable)
log1("another_variable", another_variable)
log1("some_variable", some_variable, "another_variable", another_variable) // results in a compile time error
log1() // results in a compile time error
A more efficient approach would be
log2({some_variable})
log2({another_variable})
To achieve this, I can create a function
const log2 = (obj: { [key: string]: any }) => {
const keys = Object.keys(obj)
if( keys.length !== 1 ) throw new Error("only one key is expected")
const key = keys[0]
console.log(key, obj[key])
}
However,
log2({some_variable, another_variable}) // compiles but results in a run time error
log2({}) // compiles but results in a run time error
I want to force compilation errors on lines like log2({v1, v2})
and log2({})
.
I aim to eliminate dynamic type checks and ensure that there is a compile time check to validate that the obj
parameter has only one key, or an exact number of keys with names that are unknown to me.