xingfrontend
xingfrontend

Reputation: 21

Why `type a = {} extends {a?:number}? true:false;` is true

Why type a = {} extends {a?:number}? true:false; is true, but type b = {a?:number} extends {}? true:false; is true too!
I think the {} is a super type and it can't extends any types, but if here is a type which all properties of are optional(?), {} will extends this type, why ?
The core problem is how to judge compatibility betweens types.Before meeting this problem, i always use Set theory to explain them, but it's ineffective for this problem, so i need a new theory, unless typescript did something special to {}

Upvotes: 2

Views: 128

Answers (1)

Anastasia
Anastasia

Reputation: 802

You could interpret extends as 'can be assigned to'. Therefore, {} extends any type where all properties are optional.

const a: { a?: string, b?: number } = {}; // legal, no error

Upvotes: 1

Related Questions