Search code examples
arraystypescripttypestypeofkeyof

How can I resolve ts(2339) when using keyof typeof on a custom Type?


The Problem

The TypeScript at the bottom of this post results in the following error:

Property 'push' does not exist on type '{ title: string; outline: string; why: string; additional: string; }'.ts(2339)

I understand why the error occurs, I just can't figure out how to resolve it. Ideally I'd exclude the idea key from the list of possible keys to push to, but I'm not sure how.

The TypeScript

type Idea = {
    challenges: Array<string>,
    personas: Array<string>,
    experiences: Array<string>,
    idea: {
        title: string,
        outline: string,
        why: string,
        additional: string,
    }
};

let idea:Idea = {
    challenges: [],
    personas: [],
    experiences: [],
    idea: {
        title: "",
        outline: "",
        why: "",
        additional: "",
    }
};

function addtoIdea(ideaItem:string, uniqueId:string){
    idea[ideaItem as keyof typeof idea].push(uniqueId);        
}

addtoIdea("challenges","abcd1234");

Solution

  • As mentioned in my comment, you need to first make sure that the property you're trying to push into is an Array first:

    type Idea = {
        challenges: Array<string>,
        personas: Array<string>,
        experiences: Array<string>,
        idea: {
            title: string,
            outline: string,
            why: string,
            additional: string,
        }
    };
    
    let idea:Idea = {
        challenges: [],
        personas: [],
        experiences: [],
        idea: {
            title: "",
            outline: "",
            why: "",
            additional: "",
        }
    };
    
    function addtoIdea(ideaItem:string, uniqueId:string){
        const prop = idea[ideaItem as keyof typeof idea]; // string[] | { ... }
        if(Array.isArray(prop)){
                prop.push(uniqueId); // prop is string[] 
        }    
    }
    
    addtoIdea("challenges","abcd1234");
    

    Working playground