首页 > 解决方案 > 打字稿按属性类型省略或排除

问题描述

我想根据这些属性的类型创建一个仅具有父类型的某些属性的新类型。

例如,我想要一个只包含字符串的 Post 类型。

type Post = {
  id: string;
  title: string;
  numberOfLikes: number;
  ...
}

// This doesn't work
type PostStringsOnly = Extract<Post, string>

const postOnlyWithStringKeys: PostStringsOnly = {
  id: "123",
  title: "The best post!"
}

我想将它用于我不知道前面所有键的通用类型。所以特别省略“numberOfLikes”是行不通的。它需要按类型。

标签: typescript

解决方案


type Post = {
  id: string;
  title: string;
  numberOfLikes: number
}

type PostStringsOnly = Omit<Post, 'numberOfLikes'>

const postOnlyWithStringKeys: PostStringsOnly = {
  id: "123",
  title: "The best post!"
}

推荐阅读