Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to roop typescript's type for params?

If I set listData[index][field] = newValue as any, it’s working, but I don’t want to use any.

I still try to use newValue: string | number | Date still shows the error

How do I let the typescript working for the setting listData[index][field] = newValue ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface Sons {
  name: string;
  address?: string;
  date?: Date;
  age?: number;
}

interface Parents extends Sons {
  height: string;
}

const parentList: Parents = {
  name: '',
  height: '',
}

const listData: Parents[] = [parentList]


class Test {
  update<K extends keyof Parents>(index: number, field: K, newValue: string ) {
    // Type 'string' is not assignable to type 'Parents[K]'.
    // Type 'string' is not assignable to type 'never'
    listData[index][field] = newValue
}

>Solution :

You can use Parents[K] instead of string for newValue. This is called an Indexed Access type which dynamically looks up the type of a given property key (K) on the Parents interface.

interface Sons {
  name: string;
  address?: string;
  date?: Date;
  age?: number;
}

interface Parents extends Sons {
  height: string;
}

const parentList: Parents = {
  name: '',
  height: '',
}

const listData: Parents[] = [parentList]


class Test {
  update<K extends keyof Parents>(index: number, field: K, newValue: Parents[K] ) {
    listData[index][field] = newValue;
  }
}

declare const test: Test;

test.update(0, "height", "very tall");
test.update(0, "date", new Date());

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading