TypeScript - 如何从 TypeScript 的接口中挑选一些属性?

pea*_*nut 13 typescript

例如,我为这样的帖子定义了一个结构:

interface PostsInfo{
    md_content    :string;
    id            :number;
    title         :string;
    description   :string;
    update_time   :Date;
    create_time   :Date;
    comment_count :number;
}
Run Code Online (Sandbox Code Playgroud)

然后,我需要一个没有属性的其他接口,即md_content.

interface PostsInfoWithoutContent{
    // How define?
}
Run Code Online (Sandbox Code Playgroud)

它现在可以解决这个问题, make PostsInfoextend PostsInfoWithoutContent,但是,如果我喜欢那样,当我需要时我该怎么做PostsInfoWithoutCommentcomment_count从 中删除PostsInfo)?

Tit*_*mir 24

您可以使用内置 Pick 类型来获取接口的一部分:

type PostsInfoWithoutConent= Pick<PostsInfo, "id" | "title">
Run Code Online (Sandbox Code Playgroud)

如果您只想排除一个属性,最好定义Omit类型并使用它

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">
Run Code Online (Sandbox Code Playgroud)