Skip to content

Instantly share code, notes, and snippets.

@stephenh
Created July 9, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenh/eb95673ef194aa7fcd873f28e036ab94 to your computer and use it in GitHub Desktop.
Save stephenh/eb95673ef194aa7fcd873f28e036ab94 to your computer and use it in GitHub Desktop.
ExactType
type Args = {
id?: string | undefined | null;
firstName?: string | undefined | null;
parentId?: string | undefined | null;
different?: string | undefined | null;
};
type Opts = {
id?: string | undefined | null;
firstName?: string | undefined | null;
parent?: string | undefined | null;
};
const a: Args = null!;
// I want parentId and different to be type failures
const o: Opts = a;
function doOpts(o: Opts): void {}
function onlyOpts<T extends Opts>(o: Exact<Opts, T>): void {}
function onlyOpts2<O>(o: Exact<Opts, O>): void {
doOpts(o);
}
onlyOpts(a);
onlyOpts2(a);
onlyOpts({ firstName: "as" });
onlyOpts({ parent: "as" });
type Impossible<K extends keyof any> = {
[P in K]: never;
};
// T is the exact type, U is the user's passed type,
type Exact<T, U> = T & U & Impossible<Exclude<keyof U, keyof T>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment