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
)?
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.
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.
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.
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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With