0

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.
1
  • 1
    use U instead of keyof T for the parameter? eg: newText<T, U extends keyof T>(name: U, value: T[U]){...}? Commented Nov 13, 2017 at 23:32

1 Answer 1

1

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.

Simple:

type T = { one: Function, two: string };
declare function newText<KEY extends keyof T>(name: KEY, value: T[KEY]): any;

newText('one', () => null); // Okay
newText('two', () => null); // Error 

Cheers 🍻🌹

Sign up to request clarification or add additional context in comments.

1 Comment

Yep that is what I thought. My actual use case is more complicated because I am wrapping my class in some helper functions (I wanted to stay compatible with old usage so I couldn't change the types). doing this fixed my more complicated version. I added the full use case to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.