Seeking to utilize type inference and checking in a generic property within the compiler. Here is an example:
type Args<T, O extends object> = {
instance: O,
key: { [K in keyof O]: T extends O[K] ? K : never }[keyof O]
};
class C<T> {
public fn<O extends object>(args: Args<T, O>): void { }
}
The Args
object contains a key k
, where something of type
T</code can be assigned to <code>k
.
This class usage looks like:
type Test = { a: string, b: number };
let test: Test = { a: "", b: 2 };
let c = new C<string>();
c.fn({ instance: test, key: "a" }); // works as expected
c.fn({ instance: test, key: "b" }); // error as expected
This allows for inferred type parameter O
, checked type of key
, and suggested options for key
.
Wanting to use an Args
object with C<T>.fn
as a property in other classes without knowing the type of
O</code yet leads to type checking issues with <code>any
:
interface I<T> {
args: Args<T, any>;
}
let i: I<string>;
i = { args: { instance: test, key: "b" } }; // no error
Attempting with a lambda instead:
interface I2<T> {
args: <O extends object>() => Args<T, O>;
}
let i2: I2<string>;
i2 = { args: () => ({ instance: test, key: "a" }) }; // Type 'Test' is not assignable to type 'O'. ???
c.fn(i.args);
Puzzled by the type error.
How can types be ensured to infer and check for a property of an interface similar to a generic function?