Recap: Building Typed Funcs
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 29 of 73.
Challenge
EasyCreate a function named formatName that takes three parameters: firstName of type string (required), lastName of type string (required), and middleName of type string (optional). The function should return a formatted full name as a string with an explicit return type annotation.
When all three parameters are provided, the function should return the name in the format: "[firstName] [middleName] [lastName]"
When only the first and last names are provided, the function should return the name in the format: "[firstName] [lastName]"
The following inputs will be provided:
- First input:
firstNameas a string - Second input:
lastNameas a string - Third input:
middleNameas a string (this may be an empty string""to indicate no middle name)
Your function should treat an empty string for middleName the same as if no middle name was provided.
Read the three inputs, call your formatName function with the appropriate parameters, and print the result.
Note: If the third input is an empty string, call the function with only the first two parameters (do not pass the empty string as the middle name).
Try it yourself
import * as fs from "fs";
// Read inputs
const stdinBuffer: Buffer = fs.readFileSync(0);
const inputs: string[] = stdinBuffer.toString().trim().split('\n');
const firstName: string = inputs[0];
const lastName: string = inputs[1];
const middleName: string = inputs[2];
// TODO: Write your code here
// Create the formatName function with proper type annotations
// Call the function and output the result
// Remember to handle the case where middleName is an empty string
console.log(result);All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples