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.
Code
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 notesInside 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.