TypeScript-如何从TypeScript中的接口中提取一些属性?
e、 g.我为这样的职位定义了一个结构:TypeScript-如何从TypeScript中的接口中提取一些属性?,typescript,Typescript,e、 g.我为这样的职位定义了一个结构: interface PostsInfo{ md_content :string; id :number; title :string; description :string; update_time :Date; create_time :Date; comment_count :number; } 然后,我需要一个没有属性的其他接口,md
interface PostsInfo{
md_content :string;
id :number;
title :string;
description :string;
update_time :Date;
create_time :Date;
comment_count :number;
}
然后,我需要一个没有属性的其他接口,md\u content
interface PostsInfoWithoutContent{
// How define?
}
它现在就可以解决这个问题,使
PostsInfo
扩展postsinfowithout content
,但是,如果我这样做,当我需要postsinfowithout comment
(从PostsInfo
中删除comment\u count
)时,我该怎么做呢?您可以使用内置拾取类型来获取接口的一部分:
type PostsInfoWithoutConent= Pick<PostsInfo, "id" | "title">
type postsinfowithout conent=Pick
如果只想排除一个属性,最好定义类型并使用该属性
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">
type Diff=({[P in T]:P}&{[P in U]:never}&{[x:string]:never}[T];
类型省略=拾取;
键入PostsInfoWithoutContent=省略
在TypeScript 2.7.1中,使用type postsinfowithout conent=Omit
,TypeScript告诉我错误TS1003:需要标识符。删除typeof
it wosks@花生豌豆很抱歉,修复了,我有一个自定义编译器