#New to TypeScript and Next.js. Trying to use an object key from a JSON file dynamically

39 messages · Page 1 of 1 (latest)

wicked coral
#

Code snippets Gist in comments. The JSON file is where the data is being pulled from and into the tsx file.

As you can see, the currentFolder value is using state and is currently holding a value of "experience" as that's the first item in the info object in "developerConfig.about.sections.professional-info.info". This value is printing to the console just fine and is displaying in the first H1 just fine too. However, when i try to use it dynamically in the second H1 when calling the description value in "developerConfig.about.sections["professional-info"].info["experience"].title" it all falls apart.

The error message is as follows:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ experience: { title: string; description: string; }; "hard-skills": { title: string; description: string; }; "soft-skills": { title: string; description: string; }; }'.
  No index signature with a parameter of type 'string' was found on type '{ experience: { title: string; description: string; }; "hard-skills": { title: string; description: string; }; "soft-skills": { title: string; description: string; }; }'.

As a TypeScript and Next.js newbie I don't know if this is a TypeScript issue or a Next.js issue. AI has been no help, I've tried their suggestions of adding interfaces and declaring types but since im new, i dont know if im doing it wrong.

Where am i going wrong here?

#

My aim here is to have the value as state so i can change it's state based on button clicks. For example a button that says "soft-skills" will change the state of currentFolder to "soft-skills", leading that object's content to be displayed instead of "experience"

naive sundial
#

!:unsafe-keys

fresh raptorBOT
#
retsam19#0
`!retsam19:unsafe-keys`:

Since TS allows objects to have extra properties not specified in the type, it doesn't assume that all the keys on the type are the only keys on the object. This means that Object.keys returns string[] not a specific type, and for(const key in obj), key is string, (not keyof typeof obj).

If you wish to assume otherwise, this utility is often helpful:

// A signature for `Object.keys` that assumes the only keys are the ones indicated by the type
const unsafeKeys = Object.keys as <T>(obj: T) => Array<keyof T>;
naive sundial
#

the problem is how you are doing Object.keys there, then later using the value as an index

#

here's a simpler/more-self-contained example:

fresh raptorBOT
#
mkantor#0

Preview:```ts
import React, {useState} from "react"

const info = {
experience: {
title: "experience",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
},
}

export default function ProfessionalContent() {
const
...```

naive sundial
#

i might be able to give some suggestions if you can tell me more about what you are trying to do. the profContentFolders[0] looks like you're arbitrarily picking the first property, even though JSON object properties are not really ordered

#

should that always be 'experience' perhaps?

wicked coral
wicked coral
# naive sundial i might be able to give some suggestions if you can tell me more about what you ...

So the developer.json object is being used in my portfolio, that's what im currently building. I have a top/horizonal navbar tab labelled "about-me", when users click on this i want them to see a vertical sidebar on the left which will be a subnav for about-me only. The nav items in that sidebar should be the values "professional-info", "personal-info" and "hobbies-info" as seen on the JSON file in the sections. Then when users click on one of those 3 sidebar items, they should be presented with another inner sidebar with the same thing being done here except the values are now "experience", "hard-skills" and "soft-skills" in the case of the "professional-info" section key. But i want "experience" to be the default selected value when employers click on "professional-info". Thats why i left the index value as 0. Upon clicking "experience" the user should then see the description text in "experience.description" that is pulled from the JSON file. As you can see, if i can figure out a way to make the "experience" object key dynamic, all i need to do is change that as state and then the displayed content should update if the state is changed to "soft-skills" for example. Displaying "soft-skills.description" and so on and so forth

wicked coral
# naive sundial i might be able to give some suggestions if you can tell me more about what you ...

As further context, this is the design I'm trying to create. This guy created it in Vue, but i want to create it in Next.js for my own portfolio. As you can see, when you click on about-me at the top, the nested folder structure i described is there (icons on far left are sections, which change the inner folders when clicked): https://developer-portfolio-v2.netlify.app/about-me

naive sundial
#

what's the reason you want to make it so dynamic? for a personal site like this you would be in complete control of the structure, and i think your life would be simpler if you hardcoded more things

#

the data probably doesn't even need to be a .json file. it could just be a normal typescript object, then the whole structure will be statically known and you'd get all the nice stuff that comes along with that (autocomplete, more specific error messages, etc)

#

(also btw you can have multiple paragraphs in a discord message. shift+enter will make newlines without sending the message:

tada!)

wicked coral
#

Learn
something
new
every
day! lol

wicked coral
# naive sundial what's the reason you want to make it so dynamic? for a personal site like this ...

I guess i wanted to do it as a challenge to myself? idk. Im currently trying to find a junior dev job and my thinking is that this may be something asked of me in the job and i want to know how to do it, as well as improve my TS skills. But i guess you are right i could just hardcode for now and then slowly make it dynamic once its finished and live? time is of the essence after all, i need it ready so i can start applying asap

wicked coral
#

That sounds like a much better option than trying to wrestle with a JSON object tbh

naive sundial
#

just copy your JSON stuff into a .ts file and assign it to a variable

#
export const stuff = // the JSON object
naive sundial
#

the title is already in the property values too, so an array would make it less redundant

wicked coral
#

@naive sundial thankyou, I'm going to try what you said

wicked coral
#

@naive sundial using a typescript object within the component file itself solved 2 birds with 1 stone, I can now define the type/interface in there too very easily. Thankyou so much. /resolved

#

/resolved

#

Idk how to mark it solved it's not working

naive sundial
#

!resolve

fresh raptorBOT
#

@wicked coral
Because your issue seemed to be resolved, this post was marked as resolved by @naive sundial.
If your issue is not resolved, you can reopen this post by running !reopen.
If you have a different question, make a new post in #1057653400046674112.

naive sundial
#

You can see all the commands with:

#

!help

fresh raptorBOT
#
TypeScript Community
Bot Usage

Hello mkantor! Here is a list of all commands in me! To get detailed description on any specific command, do help <command>

**Help System Commands:**

helper ► Ping the @Helper role from a help post
resolved ► Mark a post as resolved
reopen ► Reopen a resolved post

**Misc Commands:**

ping ► See if the bot is alive
playground ► Shorten a TypeScript playground link
help ► Sends what you're looking at right now
handbook ► Search the TypeScript Handbook

**Reputation Commands:**

rep ► Give a different user some reputation points
history ► View a user's reputation history
leaderboard ► See who has the most reputation

**Snippet Commands:**

listSnippets ► List snippets matching an optional filter
snip ► Create or edit a snippet
deleteSnip ► Delete a snippet you own

**Twoslash Commands:**

twoslash ► Run twoslash on the latest codeblock, optionally returning the quick infos of specified symbols. You can use [email protected] or ts@next to run a specific version.

wicked coral
wicked coral
naive sundial
#

Also FYI I'm going to a friend's wedding today so will be only intermittently available on discord (if at all)

wicked coral
naive sundial
#

You can just open help threads here as needed. That way no one helper is a bottleneck, and other people can learn from the discussion