I have two different interfaces with optional keys, Obj1
and Obj2
, each having unique values:
interface Obj1 {
a?: string
b?: string
c?: number
}
interface Obj2 {
a: boolean
b: string
c: number
}
In my scenario, Obj1
is used as an argument for a function, while Obj2
represents the return type of that function. I need the return type to only include the keys present in Obj1
. For example, if Obj1
only has keys a
and b
, then Obj2
should also have only keys a
and b
.
I attempted the following approach, but encountered a TypeScript error
Type 'Property' cannot be used to index type 'ValueType'
type Obj1KeysWithObj2Values<KeyType extends Obj1, ValueType extends Obj2> = {
[Property in keyof KeyType]: ValueType[Property]
}
UPDATE: Here's how the function and its call look like:
const myFunc = <T extends Obj1>({ a, b, c }: T) => {
const returnObj: Partial<Obj2> = {}
if (a) {
returnObj.a = true
}
if (b) {
returnObj.b = '1'
}
if (c) {
returnObj.c = 20
}
return returnObj as Obj1KeysWithObj2Values<T, Obj2>
}
const resultObj = myFunc({ a: 'hello', b: 'hello' })
If you test it out, you'll notice that the resultObj
will contain whatever was passed to the function within the Obj1
interface, regardless of Obj2
.