Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - How can pick off some properties from a interface in TypeScript?

Tags:

typescript

e.g. I defined a structure for posts like this:

interface PostsInfo{
    md_content    :string;
    id            :number;
    title         :string;
    description   :string;
    update_time   :Date;
    create_time   :Date;
    comment_count :number;
}

then, I need an other interface that without a property which is md_content.

interface PostsInfoWithoutContent{
    // How define?
}

It can fix this right now that make PostsInfo extend PostsInfoWithoutContent, but, if I do like that, how can I do when I need PostsInfoWithoutComment (remove comment_count from PostsInfo)?

like image 351
pea3nut Avatar asked Feb 17 '18 08:02

pea3nut


People also ask

How do you use partial in TypeScript?

Partial Type in TypeScript In TypeScript, we can define a type as optional with a ? question mark. For example, in the below code, lastName is optional. Therefore, even though firstUser has the type User, we can leave out lastName as it is not required.

What is pick in TypeScript?

The TypeScript 'Pick' type is a utility type which is used to create a new custom Type, based off an already existing one. It is the opposite of the Omit Type. The type is very useful in creating custom types based on already existing ones.

How do I delete a property in TypeScript?

To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.

How do you inherit from another interface in TypeScript?

An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.


1 Answers

You can use the buit-in Pick type to get part of an interface :

type PostsInfoWithoutConent= Pick<PostsInfo, "id" | "title">

If you just want to exclude one property you might be better off defining the the Omit type and use that

type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];  
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>; 
type PostsInfoWithoutContent= Omit<PostsInfo, "md_content">
like image 86
Titian Cernicova-Dragomir Avatar answered Sep 18 '22 17:09

Titian Cernicova-Dragomir