Typescript - Kotlin-like copy function
In Kotlin a data class can be copied using its auto-generated copy function.
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
The copy function signature, as per documentation (Docs):
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
Can something like this be done in TypeScript?
Is this an acceptable solution, or can it be improved somehow?
export class User {
constructor(
public name: string,
public age: number) {}
copy(parameters: {
name?: string,
age?: number
}): User {
const { name, age } = parameters
return new User(name || this.name, age || this.age)
}
}
This could be solved even with a Partial<User>:
copy(partialUser: Partial<User>): User {
return new User(
partialUser.name || this.name,
partialUser.age || this.age)
}
typescript
add a comment |
In Kotlin a data class can be copied using its auto-generated copy function.
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
The copy function signature, as per documentation (Docs):
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
Can something like this be done in TypeScript?
Is this an acceptable solution, or can it be improved somehow?
export class User {
constructor(
public name: string,
public age: number) {}
copy(parameters: {
name?: string,
age?: number
}): User {
const { name, age } = parameters
return new User(name || this.name, age || this.age)
}
}
This could be solved even with a Partial<User>:
copy(partialUser: Partial<User>): User {
return new User(
partialUser.name || this.name,
partialUser.age || this.age)
}
typescript
add a comment |
In Kotlin a data class can be copied using its auto-generated copy function.
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
The copy function signature, as per documentation (Docs):
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
Can something like this be done in TypeScript?
Is this an acceptable solution, or can it be improved somehow?
export class User {
constructor(
public name: string,
public age: number) {}
copy(parameters: {
name?: string,
age?: number
}): User {
const { name, age } = parameters
return new User(name || this.name, age || this.age)
}
}
This could be solved even with a Partial<User>:
copy(partialUser: Partial<User>): User {
return new User(
partialUser.name || this.name,
partialUser.age || this.age)
}
typescript
In Kotlin a data class can be copied using its auto-generated copy function.
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
The copy function signature, as per documentation (Docs):
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
Can something like this be done in TypeScript?
Is this an acceptable solution, or can it be improved somehow?
export class User {
constructor(
public name: string,
public age: number) {}
copy(parameters: {
name?: string,
age?: number
}): User {
const { name, age } = parameters
return new User(name || this.name, age || this.age)
}
}
This could be solved even with a Partial<User>:
copy(partialUser: Partial<User>): User {
return new User(
partialUser.name || this.name,
partialUser.age || this.age)
}
typescript
typescript
edited Nov 26 '18 at 11:40
LppEdd
asked Nov 26 '18 at 11:02
LppEddLppEdd
9,40621647
9,40621647
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You can deconstruct the item as shown below:
class User {
constructor(
public name: string,
public age: number) {}
}
const jack = new User("Jack", 1);
const newJack = { ...jack, age: 2 };
This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
constructor(
public name: string,
public age: number) { }
copy(user: Pick<User, 'name' | 'age'>) {
return new User(user.name, user.age);
}
}
const jack = new User("Jack", 1);
const newJack = jack.copy({ ...jack, age: 2 });
console.log(newJack);
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example wherenewJackis the fullUser.
– Fenton
Nov 26 '18 at 11:38
Thanks! Do you findPickmore appropriate thenPartial?
– LppEdd
Nov 26 '18 at 11:39
WithPickyou say "it must have the members I state", wherasPartialsays "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care aboutcopy. So the following will be caught as an error in ourPickexample:const newJack = jack.copy({ age: 2 });
– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use(user: Pick<User>): User { ... }then. Do you think that myPartialexample was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms
– LppEdd
Nov 26 '18 at 11:44
|
show 2 more comments
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479730%2ftypescript-kotlin-like-copy-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can deconstruct the item as shown below:
class User {
constructor(
public name: string,
public age: number) {}
}
const jack = new User("Jack", 1);
const newJack = { ...jack, age: 2 };
This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
constructor(
public name: string,
public age: number) { }
copy(user: Pick<User, 'name' | 'age'>) {
return new User(user.name, user.age);
}
}
const jack = new User("Jack", 1);
const newJack = jack.copy({ ...jack, age: 2 });
console.log(newJack);
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example wherenewJackis the fullUser.
– Fenton
Nov 26 '18 at 11:38
Thanks! Do you findPickmore appropriate thenPartial?
– LppEdd
Nov 26 '18 at 11:39
WithPickyou say "it must have the members I state", wherasPartialsays "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care aboutcopy. So the following will be caught as an error in ourPickexample:const newJack = jack.copy({ age: 2 });
– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use(user: Pick<User>): User { ... }then. Do you think that myPartialexample was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms
– LppEdd
Nov 26 '18 at 11:44
|
show 2 more comments
You can deconstruct the item as shown below:
class User {
constructor(
public name: string,
public age: number) {}
}
const jack = new User("Jack", 1);
const newJack = { ...jack, age: 2 };
This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
constructor(
public name: string,
public age: number) { }
copy(user: Pick<User, 'name' | 'age'>) {
return new User(user.name, user.age);
}
}
const jack = new User("Jack", 1);
const newJack = jack.copy({ ...jack, age: 2 });
console.log(newJack);
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example wherenewJackis the fullUser.
– Fenton
Nov 26 '18 at 11:38
Thanks! Do you findPickmore appropriate thenPartial?
– LppEdd
Nov 26 '18 at 11:39
WithPickyou say "it must have the members I state", wherasPartialsays "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care aboutcopy. So the following will be caught as an error in ourPickexample:const newJack = jack.copy({ age: 2 });
– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use(user: Pick<User>): User { ... }then. Do you think that myPartialexample was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms
– LppEdd
Nov 26 '18 at 11:44
|
show 2 more comments
You can deconstruct the item as shown below:
class User {
constructor(
public name: string,
public age: number) {}
}
const jack = new User("Jack", 1);
const newJack = { ...jack, age: 2 };
This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
constructor(
public name: string,
public age: number) { }
copy(user: Pick<User, 'name' | 'age'>) {
return new User(user.name, user.age);
}
}
const jack = new User("Jack", 1);
const newJack = jack.copy({ ...jack, age: 2 });
console.log(newJack);
You can deconstruct the item as shown below:
class User {
constructor(
public name: string,
public age: number) {}
}
const jack = new User("Jack", 1);
const newJack = { ...jack, age: 2 };
This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
constructor(
public name: string,
public age: number) { }
copy(user: Pick<User, 'name' | 'age'>) {
return new User(user.name, user.age);
}
}
const jack = new User("Jack", 1);
const newJack = jack.copy({ ...jack, age: 2 });
console.log(newJack);
edited Nov 26 '18 at 11:37
answered Nov 26 '18 at 11:33
FentonFenton
157k46294318
157k46294318
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example wherenewJackis the fullUser.
– Fenton
Nov 26 '18 at 11:38
Thanks! Do you findPickmore appropriate thenPartial?
– LppEdd
Nov 26 '18 at 11:39
WithPickyou say "it must have the members I state", wherasPartialsays "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care aboutcopy. So the following will be caught as an error in ourPickexample:const newJack = jack.copy({ age: 2 });
– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use(user: Pick<User>): User { ... }then. Do you think that myPartialexample was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms
– LppEdd
Nov 26 '18 at 11:44
|
show 2 more comments
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example wherenewJackis the fullUser.
– Fenton
Nov 26 '18 at 11:38
Thanks! Do you findPickmore appropriate thenPartial?
– LppEdd
Nov 26 '18 at 11:39
WithPickyou say "it must have the members I state", wherasPartialsays "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care aboutcopy. So the following will be caught as an error in ourPickexample:const newJack = jack.copy({ age: 2 });
– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use(user: Pick<User>): User { ... }then. Do you think that myPartialexample was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms
– LppEdd
Nov 26 '18 at 11:44
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
Wouldn't I lose eventual instance / static functions?
– LppEdd
Nov 26 '18 at 11:34
I have added a wider example where
newJack is the full User.– Fenton
Nov 26 '18 at 11:38
I have added a wider example where
newJack is the full User.– Fenton
Nov 26 '18 at 11:38
Thanks! Do you find
Pick more appropriate then Partial?– LppEdd
Nov 26 '18 at 11:39
Thanks! Do you find
Pick more appropriate then Partial?– LppEdd
Nov 26 '18 at 11:39
With
Pick you say "it must have the members I state", wheras Partial says "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care about copy. So the following will be caught as an error in our Pick example: const newJack = jack.copy({ age: 2 });– Fenton
Nov 26 '18 at 11:40
With
Pick you say "it must have the members I state", wheras Partial says "I don't know what it's going to have". In our case, we can be quite strict that we expect name and age to be supplied and we don't care about copy. So the following will be caught as an error in our Pick example: const newJack = jack.copy({ age: 2 });– Fenton
Nov 26 '18 at 11:40
Interesting! I could even just use
(user: Pick<User>): User { ... } then. Do you think that my Partial example was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms– LppEdd
Nov 26 '18 at 11:44
Interesting! I could even just use
(user: Pick<User>): User { ... } then. Do you think that my Partial example was not appropriate? I ask so I'm able to understand if I'm doing right or wrong in general terms– LppEdd
Nov 26 '18 at 11:44
|
show 2 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479730%2ftypescript-kotlin-like-copy-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
