javascript - what is the most terse way to return an array of entities in typescript? -
i'm trying figure out terse way return array of objects ts function. following function works expected:
getauthors1(): author[] { var authors: author[] = [ { firstname: "john"; mi: "j"; lastname: "smith"; } ]; return authors; }
the following function errors out b/c appears ts won't let me return object array directly opposed variable:
getauthors2(): author[] { return author[] = [ { firstname: "john"; mi: "j"; lastname: "smith"; } ]; }
the following function errors out b/c value isn't provided mi:
getauthors3(): author[] { var authors: author[] = [ { firstname: "john"; lastname: "smith"; } ]; return authors; }
questions:
- are values required object properties when creating object initialized array? 1a. if case developers typically initialize property values in class?
- is there way return object array directly, similar getauthors2() example above, opposed having assign variable , return variable?
if have interface defined , create object tell typescript should of type, complain missing property, should.
one way around use mapped type state each property of object optional, , use partial< author >. see official documentation more info.
you can return array right away, remove type you've added after return:
getauthors2(): author[] { return [ { firstname: 'john', mi: 'j', lastname: 'smith', } ]; }
also wherever possible should remove manually defined types, return author[] functions. typescript use type inference figure out itself.
in specific example either leave return type defined, , typescript make required checks or use similar have in getauthors3. if or have objects typed place them in array , typescript rest:
getauthors() { const author: author = { firstname: 'john', mi: 'j', lastname: 'smith', }; return [author]; }
Comments
Post a Comment