Skip to content

Instantly share code, notes, and snippets.

@pconerly
Created April 20, 2021 19:40
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 pconerly/7cf531cb0e6c48ff2a40e0a20f281742 to your computer and use it in GitHub Desktop.
Save pconerly/7cf531cb0e6c48ff2a40e0a20f281742 to your computer and use it in GitHub Desktop.
Enforce same argument in typescript
function requireSameArgType<A>(a: A, b: A) {
return null;
}
function main() {
requireSameArgType(1, 2);
requireSameArgType('string', 'still a string');
requireSameArgType(1, 'string');
}
function requireSameObjShape<T, K extends T>(a: T, b: K) {
return null;
}
function main2() {
requireSameObjShape({ foo: 1, bar: 2 }, { foo: 2, bar: 4 });
// throws type error because arguments are different shape:
requireSameObjShape({ foo: 1, bar: 2 }, { foo: 2 });
requireSameObjShape({ foo: 1, bar: 2 }, { foo: 2, shabadoo: 4 });
requireSameObjShape({ foo: 1, bar: 2, shabadoo: 4 }, { foo: 2, shabadoo: 4 });
requireSameObjShape(
{
foo: 1,
bar: 2,
deeper: {
a: 'a',
b: 'b',
},
},
{
foo: 2,
bar: 4,
deeper: {
a: 'a',
b: 4,
},
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment