#Dynamically assign value to object

13 messages · Page 1 of 1 (latest)

wary elbow
#

Greetings!
I got a pretty simple task, I think, but I can't make it happen. I have a player object, that I wanna modify, and keep the changes in another partial object. When calling the method, I parse in the target attribute of the object and then wanna assign the new aquired value into the edited players object. But TypeScript doesnt let me do it, in terms of the type-check.

What am I doing wrong?

last terraceBOT
#
Lord Tkay#1337

Preview:```ts
type Player = {
id: number
firstName: string
lastName: string
email?: string
}

class PlayerManager {
private editedPlayer?: Partial<Player>
onInput(
event: Event,
attribute: keyof Required<Player>
) {
const target = event.target as HTM
...```

#
Gerrit0#7591

Preview:ts ... onInput( event: Event, attribute: Exclude<keyof Required<Playe ...

marsh nest
#

id is a number, but innerText is a string, so TS isn't happy

wary elbow
marsh nest
#

TS doesn't preserve narrowing with dynamic property accesses like [attribute] (in most cases, there are a couple where it does, but this isn't one of them)

#

That check also wouldn't work correctly because editedPlayer starts out empty, so the if would always be false until something was added to it

wary elbow
#

Oh, you are right. I kinda forgot about that. Would there be a way to achieve numbers and strings in a dynamic way, with keeping the type-check? so without using any

marsh nest
#

I'm pretty sure you'll need a type assertion if you want to support multiple types

#

... well, I guess you could... one sec

last terraceBOT
#
Gerrit0#7591

Preview:ts ... onInputString( event: Event, attribute: KeysOfType<Player, string> ) { const ...

marsh nest
#

Probably not really what you're after, but...

#

If you wanted a single method, you'd need some value that you can check for the type of the attribute...