type Handlers = {
[name: string | number]: () => void
}
type H1 = {
"click": () => void
}
interface H2 {
"click": () => void
}
type A = H1 extends Handlers ? 'yes' : 'no' // yes
type B = H2 extends Handlers ? 'yes' : 'no' // no
tsc v5.1.6.
Although H1 and H2 have the same structure, I obtained that A is 'yes' and B is 'no'.
It seems that there are some differences between type and interface in the extends clause. I have read the typescript manual twice, but I cannot find any relevant explanations.
I don't know if it is related to some of the underlying logic of TSC?
Is the type checking of the Interface stricter than that of the Type?
type can represent a wide range of types, including primitive types, unions, intersections, etc.
interface is more focused on object shape definition and can be extended by other interfaces.
type works as expected in conditional types and the conditional type checks if the specified type is assignable to another type.
interface in conditional types behaves differently. TypeScript's conditional types use structural compatibility for checks, and interfaces are open-ended.
H1 extends Handlers because it matches the structure exactly, so type A = 'yes'. H2 doesn't extend Handlers in a conditional type context due to the difference in behavior between type and interface, so type B = 'no'.
Example:-
Type:-
Interface:-