Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

I am a typescript developer. How can I type "key" in this code: const foo = (af: A B) =>…

  1. User

    I am a typescript developer. How can I type "key" in this code:

    const foo = (af: A | B) => { for (const key in af) { console.log(af[key]) } }

    key is a string but I need to restrict the type of key to A if af is A, or B if af is B

  2. Assistant

    To restrict the type of key in the for...in loop based on the type of af, you can use generics and conditional types. Here's an example of how you can achieve this in TypeScript:

    type A = {
      propA: string;
    };
    
    type B = {
      propB: number;
    };
    
    const foo = <T extends A | B>(af: T) => {
      for (const key in af) {
        if ('propA' in af && key === 'propA') {
          const propAValue: string = af[key]; // Type of key is restricted to 'propA' if af is of type A
          console.log(propAValue);
        } else if ('propB' in af && key === 'propB') {
          const propBValue: number = af[key]; // Type of key is restricted to 'propB' if af is of type B
          console.log(propBValue);
        }
      }
    }
    

    In this example, we use a generic type T that extends A or B (T extends A | B). Inside the for...in loop, we check if the property name exists in the object to determine the actual type of af (i.e., A or B). Based on that, we can safely assign and type af[key] accordingly.

  3. User

    I want another solution using keyof

  4. Assistant

    If you want to use keyof to restrict the type of key, you can use conditional types along with mapped types. Here's an alternative solution using keyof:

    type A = {
      propA: string;
    };
    
    type B = {
      propB: number;
    };
    
    const foo = (af: A | B) => {
      type Key = keyof (A & B); // Get the common keys of A and B
    
      for (const key in af) {
        if (key in af && key as Key === 'propA') {
          const propAValue: string = af[key as Key]; // Type of key is restricted to 'propA' if af is of type A
          console.log(propAValue);
        } else if (key in af && key as Key === 'propB') {
          const propBValue: number = af[key as Key]; // Type of key is restricted to 'propB' if af is of type B
          console.log(propBValue);
        }
      }
    }
    

    In this approach, we define a new type Key using the keyof operator on the intersection (&) of A and B. This will give us the common keys between A and B. Then, within the for...in loop, we can check if key exists in af and if it matches the expected key using key as Key. This allows us to restrict the type of key based on the type of af.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.