Created
April 20, 2021 19:40
-
-
Save pconerly/7cf531cb0e6c48ff2a40e0a20f281742 to your computer and use it in GitHub Desktop.
Enforce same argument in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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