Typescript :Getter can't return array with custom typeAre strongly-typed functions as parameters possible in TypeScript?TypeScript Interface Array Type error TS2411Typescript: Interfaces vs TypesTypescript return type for Observables in getter and setterForce custom JavaScript to respect TypeScript interfacesTypescript return value typeTypeScript. How to use not exported type definitions?Typescript tells me method is property and can't create ObjectTypescript: function return type depending on input function returns typeReturn union type causing typescript not to compile

Could sidesticks be linked?

Is there any road between the CA State Route 120 and Sherman Pass Road (Forest Route 22S0) that crosses Yosemite/Serria/Sequoia National Park/Forest?

Vacuum collapse -- why do strong metals implode but glass doesn't?

Do living authors still get paid royalties for their old work?

Is "stainless" a bulk or a surface property of stainless steel?

Multicolumn in table not centered

Changing a TGV booking

What happened after the end of the Truman Show?

Nuclear decay triggers

Chord with lyrics - What does it mean if there is an empty space instead of a Chord?

Default camera device to show screen instead of physical camera

How to dismiss intrusive questions from a colleague with whom I don't work?

Do predators tend to have vertical slit pupils versus horizontal for prey animals?

Are required indicators necessary for radio buttons?

Metal that glows when near pieces of itself

Is it allowable to use an organization's name to publish a paper in a conference, even after I graduate from it?

Use of vor in this sentence

Label on a bended arrow

E: Sub-process /usr/bin/dpkg returned an error code (1) - but how do I find the meaningful error messages in APT's output?

Have only girls been born for a long time in this village?

Chess software to analyze games

Levenshtein Neighbours

TechSupport Issue ID#812

What animal has fat with the highest energy density?



Typescript :Getter can't return array with custom type


Are strongly-typed functions as parameters possible in TypeScript?TypeScript Interface Array Type error TS2411Typescript: Interfaces vs TypesTypescript return type for Observables in getter and setterForce custom JavaScript to respect TypeScript interfacesTypescript return value typeTypeScript. How to use not exported type definitions?Typescript tells me method is property and can't create ObjectTypescript: function return type depending on input function returns typeReturn union type causing typescript not to compile






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Im getting errors when trying to return array with custom type from getter. Here is the error message:



Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority


And here is my code:



import Expense from '../interfaces/expence';

class User
firstName: string;
lastName: string;
totalCost: number;
private expenses: Expense[];
constructor(firstName: string, lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;

set userExpenses(expence: Expense)
this.expenses = [...this.expenses, expence]
this.totalCost += expence.cost

get userExpenses()
return this.expenses


export default User;

interface Expense
name: string
cost: number;
priority: string,


export default Expense;









share|improve this question


























  • Is the whole code from one single file?

    – Nino Filiu
    Mar 27 at 14:47











  • Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

    – Titian Cernicova-Dragomir
    Mar 27 at 14:50











  • No, they are from separate files.Is there an alternative way i could do this.

    – Ktr1000
    Mar 27 at 14:55












  • On a side note, you've got typos: expence instead of expense

    – Nino Filiu
    Mar 27 at 14:58


















0















Im getting errors when trying to return array with custom type from getter. Here is the error message:



Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority


And here is my code:



import Expense from '../interfaces/expence';

class User
firstName: string;
lastName: string;
totalCost: number;
private expenses: Expense[];
constructor(firstName: string, lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;

set userExpenses(expence: Expense)
this.expenses = [...this.expenses, expence]
this.totalCost += expence.cost

get userExpenses()
return this.expenses


export default User;

interface Expense
name: string
cost: number;
priority: string,


export default Expense;









share|improve this question


























  • Is the whole code from one single file?

    – Nino Filiu
    Mar 27 at 14:47











  • Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

    – Titian Cernicova-Dragomir
    Mar 27 at 14:50











  • No, they are from separate files.Is there an alternative way i could do this.

    – Ktr1000
    Mar 27 at 14:55












  • On a side note, you've got typos: expence instead of expense

    – Nino Filiu
    Mar 27 at 14:58














0












0








0








Im getting errors when trying to return array with custom type from getter. Here is the error message:



Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority


And here is my code:



import Expense from '../interfaces/expence';

class User
firstName: string;
lastName: string;
totalCost: number;
private expenses: Expense[];
constructor(firstName: string, lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;

set userExpenses(expence: Expense)
this.expenses = [...this.expenses, expence]
this.totalCost += expence.cost

get userExpenses()
return this.expenses


export default User;

interface Expense
name: string
cost: number;
priority: string,


export default Expense;









share|improve this question
















Im getting errors when trying to return array with custom type from getter. Here is the error message:



Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority


And here is my code:



import Expense from '../interfaces/expence';

class User
firstName: string;
lastName: string;
totalCost: number;
private expenses: Expense[];
constructor(firstName: string, lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;

set userExpenses(expence: Expense)
this.expenses = [...this.expenses, expence]
this.totalCost += expence.cost

get userExpenses()
return this.expenses


export default User;

interface Expense
name: string
cost: number;
priority: string,


export default Expense;






javascript typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 14:47









Nino Filiu

4,3975 gold badges17 silver badges34 bronze badges




4,3975 gold badges17 silver badges34 bronze badges










asked Mar 27 at 14:44









Ktr1000Ktr1000

638 bronze badges




638 bronze badges















  • Is the whole code from one single file?

    – Nino Filiu
    Mar 27 at 14:47











  • Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

    – Titian Cernicova-Dragomir
    Mar 27 at 14:50











  • No, they are from separate files.Is there an alternative way i could do this.

    – Ktr1000
    Mar 27 at 14:55












  • On a side note, you've got typos: expence instead of expense

    – Nino Filiu
    Mar 27 at 14:58


















  • Is the whole code from one single file?

    – Nino Filiu
    Mar 27 at 14:47











  • Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

    – Titian Cernicova-Dragomir
    Mar 27 at 14:50











  • No, they are from separate files.Is there an alternative way i could do this.

    – Ktr1000
    Mar 27 at 14:55












  • On a side note, you've got typos: expence instead of expense

    – Nino Filiu
    Mar 27 at 14:58

















Is the whole code from one single file?

– Nino Filiu
Mar 27 at 14:47





Is the whole code from one single file?

– Nino Filiu
Mar 27 at 14:47













Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

– Titian Cernicova-Dragomir
Mar 27 at 14:50





Getter/seter must have the same type. In your case you want the setter to take an item and the getter to return the array. this is not possible.

– Titian Cernicova-Dragomir
Mar 27 at 14:50













No, they are from separate files.Is there an alternative way i could do this.

– Ktr1000
Mar 27 at 14:55






No, they are from separate files.Is there an alternative way i could do this.

– Ktr1000
Mar 27 at 14:55














On a side note, you've got typos: expence instead of expense

– Nino Filiu
Mar 27 at 14:58






On a side note, you've got typos: expence instead of expense

– Nino Filiu
Mar 27 at 14:58













1 Answer
1






active

oldest

votes


















2














The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].



Better solution would be create a append method for setter, as following code would not make sense



user.userExpenses = new Expense("1", 100, "1"); \ it appends to expenses array


Here's what I would do



class User 
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;


set userExpenses(expences: Expense[]) //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);


get userExpenses()
return this.expenses


addExpences(expences: Expense[]) //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];








share|improve this answer

























  • Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

    – Spencer Pollock
    Mar 27 at 15:29










Your Answer






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



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380032%2ftypescript-getter-cant-return-array-with-custom-type%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









2














The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].



Better solution would be create a append method for setter, as following code would not make sense



user.userExpenses = new Expense("1", 100, "1"); \ it appends to expenses array


Here's what I would do



class User 
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;


set userExpenses(expences: Expense[]) //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);


get userExpenses()
return this.expenses


addExpences(expences: Expense[]) //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];








share|improve this answer

























  • Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

    – Spencer Pollock
    Mar 27 at 15:29















2














The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].



Better solution would be create a append method for setter, as following code would not make sense



user.userExpenses = new Expense("1", 100, "1"); \ it appends to expenses array


Here's what I would do



class User 
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;


set userExpenses(expences: Expense[]) //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);


get userExpenses()
return this.expenses


addExpences(expences: Expense[]) //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];








share|improve this answer

























  • Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

    – Spencer Pollock
    Mar 27 at 15:29













2












2








2







The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].



Better solution would be create a append method for setter, as following code would not make sense



user.userExpenses = new Expense("1", 100, "1"); \ it appends to expenses array


Here's what I would do



class User 
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;


set userExpenses(expences: Expense[]) //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);


get userExpenses()
return this.expenses


addExpences(expences: Expense[]) //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];








share|improve this answer













The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].



Better solution would be create a append method for setter, as following code would not make sense



user.userExpenses = new Expense("1", 100, "1"); \ it appends to expenses array


Here's what I would do



class User 
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string)
this.firstName = firstName;
this.lastName = this.lastName;


set userExpenses(expences: Expense[]) //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);


get userExpenses()
return this.expenses


addExpences(expences: Expense[]) //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];









share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 15:01









Tanmay_vijayTanmay_vijay

3511 silver badge11 bronze badges




3511 silver badge11 bronze badges















  • Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

    – Spencer Pollock
    Mar 27 at 15:29

















  • Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

    – Spencer Pollock
    Mar 27 at 15:29
















Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

– Spencer Pollock
Mar 27 at 15:29





Great solution. It's quite annoying how get/set have to be the same type, however, it would defeat the purpose of TypeScript if it wasn't!

– Spencer Pollock
Mar 27 at 15:29








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55380032%2ftypescript-getter-cant-return-array-with-custom-type%23new-answer', 'question_page');

);

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







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript