RequiredBy Makes Selected Keys Required

Derive a variant of a draft type where chosen keys become required, while another helper turns selected keys back into optional ones.

TypescriptConfig Management

Code

typescriptsnippet
28 lines
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' };

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

RequiredBy Makes Selected Keys Required keeps everything in the function publish.

Putting it to use

The primary signature is function publish(input: Ready)

Running the file prints labeled results such as ready:, preview keys: — each operation’s effect is visible in the output.

Core lines

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;

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `publish` at load time.