← 中文资源

简体中文版本

RequiredBy 把指定键变为必填

从草稿类型派生出必填版本,同时提供反向工具把选定键降级为可选。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ready: p-1 Release notes
preview keys: id,title
p-1:Release notes

实现说明

承担主要工作的是函数 publish。

使用要点

  • 每一步打印都带着自己的标签:ready:、preview keys:。

常见问题

需要安装第三方包吗?

不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 publish。

主要签名是 function publish(input: Ready)

核心语句

type OptionalBy<T, K extends keyof T> = Omit<T, K> & { [P in K]?: T[P] };
type RequiredBy<T, K extends keyof T> = T & { [P in K]-?: T[P] };
return input.id + ':' + input.title;

代码示例

type RequiredBy<T, K extends keyof T> = T & { [P in K]-?: T[P] };
type OptionalBy<T, K extends keyof T> = Omit<T, K> & { [P in K]?: T[P] };

interface Draft {
  id?: string;
  title?: string;
  body?: string;
  publishedAt?: string;
}

// 提交前必须有 id 与 title
type Ready = RequiredBy<Draft, 'id' | 'title'>;

const ready: Ready = { id: 'p-1', title: 'Release notes' };
console.log('ready:', ready.id, ready.title);

// 反过来把某些键降级为可选
type Preview = OptionalBy<Draft, 'body' | 'publishedAt'>;
const preview: Preview = { id: 'p-2', title: 'Draft' };
console.log('preview keys:', Object.keys(preview).join(','));

function publish(input: Ready): string {
  return input.id + ':' + input.title;
}
console.log(publish(ready));

// 缺少必填键时编译失败
// const incomplete: Ready = { id: 'p-3' };