Is there a way to create a conditional type that can determine if an object is empty?
For instance:
function test<T>(a: T): T extends {} ? string : never {
return null
}
let o1: {}
let o2: { fox? }
let o3: { fox }
test(o1)
test(o2)
test(o3) // this should be 'never'
Even though the conditional type also takes inheritance into account, in all 3 cases it returns 'string' but I actually want it to return 'never' if any property of the type is required (like o3
)
UPDATE
When writing this question, my goal was to address a specific issue. I wanted to clarify my doubts rather than focus on the problem at hand and keep the question simple. Unfortunately, the answers I received did not quite hit the mark.
Essentially, I was attempting to create a function where the first argument is an object and the second one is optional only when the first argument can be completely partial (initialized with {}).
function test<T extends {}>(a: T, ...x: T extends {} ? [never?] : [any])
function test(a, b) {
return null
}
let o1: {}
let o2: { fox? }
let o3: { fox }
test(o1) // should work
test(o2) // should work
test(o3) // should fail and require a second argument