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 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)

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

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

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