简体   繁体   中英

Why the built-in type Partial of Typescript cannot use Interface

It is well known that TS integrates some complex types internally, such as Partial

type Partial<T> = {
    [P in keyof T]?: T[P];
};

But I got a lot of error when I used interface to define Partial like this

interface TPartial<T> {
  [P in keyof T]?: T[P];
};

enter image description here

Maybe my understanding of interface and type is not enough. I always thought they could be used to define object

Can anyone explain why it can't be used here

The utility type Partial<Type> that you've shown is an example of what is called a mapped type , and mapped types are defined using type aliases . It's not more complicated than that: it's just how mapped types work — you can't define them using interfaces.

To better understand the differences between aliases and interfaces, you can study the section of the TypeScript handbook called Differences Between Type Aliases and Interfaces .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM