'Typescript check the function input parameters if they contain same properties
I need a function that takes two objects A and B and returns a string.
However, the properties of A and B should be all unique: no property should be in both objects. And I want the compiler to typecheck that for me.
myFunction({a:1}, {b:1, c:1}) // Should be OK
myFunction({a:1}, {a:1, b:1, c:1}) // Should NOT be OK, since both objects contain "a"
This is what I got so far, but I run into Type parameter 'B' has a circular constraint.ts(2313) error.
type Exclude<T, U> = T extends U ? never : U
function myFunction<A, B extends Exclude<A,B>,>(a:A, b:B) : Exclude<A,B> {
// do something with a and b here
return 's' as any // would be nice if I don't need to cast here
}
const x = myFunction({a:1}, {a:1}) // Should produce an typescript error
Any ideas?
Solution 1:[1]
so i got it working (partly):
type Exclude<A, U> = U extends A ? never : U;
function myFunction<
T extends object,
U extends Exclude<T, P>,
P extends object = U
>(a: T, b: U) {
return "something";
}
myFunction({ a: 1 }, { a: 1 }); // Error
myFunction({ a: 1 }, { b: 1 }); // OK
https://codesandbox.io/s/quirky-davinci-72nvqs?file=/src/index.ts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | abnormi |
