Migrating from javascript to TypeScript
In javascript, I was able to make partial changes using the key of the object as shown below.
The typecrypt has not been able to do this because the type gets in trouble.
Is it impossible to stand on your hands with Typescript?
There is a lot of logic to update some of the huge objects, so I would like to make it happen somehow...
javascript
let profile={
name: 'Testo Taro',
age: 30,
tel: '090-0000-0000'
}
updateProfile(pram)=>{
Object.keys(pram).forEach(key)=>{
profile [key] = pram [key]
})
}
updateName() = > {
// I just want to rewrite the name
updateProfile({name:'Test Hanako')
}
TypeScript
interface Profile {
name —string
age —number
tel —string
}
let profile: Profile = {
name: 'Testo Taro',
age: 30,
tel: '090-0000-0000'
}
updateName() = > {
// I just want to rewrite the name
updateProfile({name:'Test Hanako')
}
updateProfile(pram:object)=>{
// get in trouble for one's key form
Object.keys(pram).forEach(key)=>{
profile [key] = pram [key]
})
// I can't use keyof.
Object.keys(pram).forEach(key)=>{
const v —key of Profile = key
const name = profile [v]
})
}
If the structure of the object is one-dimensional, you can use Partial
and Spread Operator to write:
interface Profile {
name —string
age —number
tel —string
}
let profile: Profile = {
name: 'Testo Taro',
age: 30,
tel: '090-0000-0000,
}
constupdateProfile=(params:Partial<Profile>)=>{
profile={...profile,...params};
}
constupdateName=()=>{
updateProfile({name:'Test Hanako')
}
updateName();
console.log(profile)
I'm learning, but
interface Profile {
key:string —string | number
name —string
age —number
tel —string
}
constupdateProfile=(params:Partial<Profile>)=>{
profile [key] = pram [key]!;
}
How about
© 2024 OneMinuteCode. All rights reserved.