I have a function
newText<T, U extends keyof T>(name: keyof T, value: T[U]){...}
If I call it with T looking like { one: Function, two: string } the types should looks like 'one' | 'two' for one and Function | string for value.
This is super close to what I want but when I specify a name I want the value to be the type of that key. So if I do newText('one', I would want to see Function as my only option for value and doing newText('two', () =>{}) should throw an error.
Is this possible in typescript 2.6?
Full use case with solution
type params = {
util?: Function;
utilName?: string;
other?: string;
};
type utilParams = 'util' | 'utilName';
class field {
name: string;
required: boolean;
value: any;
params: params;
constructor(name: string, required: boolean, value: any, params: params) {
this.name = name;
this.required = required;
this.value = value;
this.params = params;
}
}
type coreOptional<T, U extends keyof T> = {
required?: boolean;
value?: T[U];
};
class test<T> {
test<U extends keyof T>(name: keyof T, optional: coreOptional<T, U> & Partial<Pick<params, utilParams>>) {
let onlyParams: Partial<Pick<params, utilParams>> = { ...optional };
return new field(name, optional.required || false, optional.value, onlyParams);
}
}
let myTest = new test<{ one: Function; two: Function }>();
myTest.test('one', { value: '' }); //works!
myTest.test('one', { value: false}); //errors like it should.
Uinstead ofkeyof Tfor the parameter? eg:newText<T, U extends keyof T>(name: U, value: T[U]){...}?