W10 Typescript

Jin Bae·2023년 1월 20일
0

스파르타코딩클럽

목록 보기
28/35


All Javascript is Typescript, but not all Typescript is Javascript.

Advantages of Typescript and its difference from Javascript: https://medium.com/geekculture/typescript-vs-javascript-e5af7ab5a331

  • Optional static typing (정적 타이핑)
  • Early bug detection
  • Improved readability
  • Code optimization

Initializing TS

The configuration tsconfig.json can be created using tsc --init.
The source files and output directory can be set in the configuration as well as control aspects of TS. Among them are:

  • noImplicitAny: Set true or false. It controls whether variables must have a known type when true. When set to false it will infer a variable without a type as an Any type.
  • strictNullChecks: When true, it controls whether null and undefined are allowed when declaring a variable.
  • strict: TS is able to catch the most errors when strict is true. This enables noImplicitAny, strictNullChecks, noImplicitThis, and stricFunctionTypes.

Transfiling Typescript

Typescript can be transpiled into Javascript. Converting from TS to JS is called transpiling and not compiling as it changes from one type of file to another.

Compiling all TS files is run with the bash code tsc, which stands for Typescript Compiler. A single file can be compiled with tsc fileName.ts.
The user can go into watch mode while compiling using tsc -w fileName.ts.

Types

Basic types:
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html

  • boolean
  • number or bigint
  • string
  • array
    - Can be declared as let list: number[] = [1, 2, 3] or let list: Array<number> = [1, 2, 3]
  • tuple: an array with a fixed number of elements whose types are known
    - Can be delcared as let x: [string, number]
  • enum (열거형):
    - Numeric enum: When there is no value assigned to the properties of an enum, the index automatically starts with 0.
// Numeric enum example
enum Color {
	Red,
	Green,
	Blue
}

const myColor = Color.Red;
console.log(myColor) // 0

const yourColor = Color.Blue;
console.log(yourColor) // 2

Numeric enums can also use reverse mapping, where in the example above, Color.Red = Color[0].
- String enum: A string value must be assigned to the enum properties to use a string enum.

// String enum example
enum Color {
	Red = "Red",
	Green = "Green",
	Blue = "Blue"
}

const myColor = Color.Red;
console.log(myColor) // "Red"

const yourColor = Color.Blue;
console.log(yourColor) // "Blue"
  • unknown: used for variables when it is unknown what type of data the variable will be used for. A variable can be assigned as an unknown type then later specify its type. Similar to any but is a safer alternative when uncertain about the type.
    - Type casting: process of overriding a type. This can be done using the as keyword or using <>.
// Type casting with 'as'
let x: unknown = 'hello';
console.log((x as string).length);

// Type casting with '<>' (does not work with TSX)
let x: unknown = 'hello';
console.log((<string>x).length);
  • any: A value can be declared with an any type to opt-out of type checking. Using the any type is discouraged.
  • Literal type (리터럴 타입): Can be used with Union types to declare type with a string, number, or boolean of a specific value.
// String literal type
type CardinalDirections = "North" | "East" | "South" | "West"

// Number literal type:
type OneToThree = 1 | 2 | 3

// Boolean literal type
type Bools = true | flase
  • Union type: Can be used with |. It specifies that the variable is either one type or the other. For example, let val: number | string signifies "val" can be either a number or a string type.
  • Intersection type: Can be used with &. It specifies that the variable can be multiple types.
type Common = {
  name: string,
  age: number,
  gender: string
}

type Animal = {
  howl: string
}

// Intersection type
type Cat = Common & Animal;

// Union type
type Dog = Common | Animal;

let dog: Dog = {
  howl: 'dogggg'
}
let cat: Cat = {
  age: 3,
  gender: 'C',
  name: 'CC',
  howl: 'cattttt'
}
  • Void type: Defines that a void function has no return value.
  • Never type: A type that can never occur. Thiscan be used for a function that always throws an error or a function that never has a return value.

More types: https://dev.to/ibrahima92/advanced-typescript-types-cheat-sheet-with-examples-5414

Class type

Same as the JS class. A class that only has a "getter" and doesn't have a "setter" is the same as setting the property as readonly. The class's setter is the class's accessor

// A class with a getter and setter
class Developer {
  private _name: string;

  get name(): string {
    return this._name;
  }

  set name(newValue: string) {
    if (newValue && newValue.length > 5) {
      throw new Error("이름이 너무 깁니다");
    }
    this._name = newValue;
  }
}

const josh = new Developer();
josh.name = "Josh";
console.log(josh.name); //Josh

export { Developer };
  • Abstract class: Acts as a certain class's inheritor and defines the shape of the properties and methods. Can be declared using abstract infront of class. A class inheriting the abstract class must exist. An instance cannot be created with an abstract class.
// Abstract class example
abstract class Developer {
  abstract coding(): void; // 'abstract'가 붙으면 상속 받은 클래스에서 무조건 구현해야 함
  drink(): void {
    console.log("drink sth");
  }
}

class FrontEndDeveloper extends Developer {
  coding(): void {
    // Developer 클래스를 상속 받은 클래스에서 무조건 정의해야 하는 메서드
    console.log("develop front");
  }
  design(): void {
    console.log("design front");
  }
}

class BackEndDeveloper extends Developer {
  coding(): void {
    // Developer 클래스를 상속 받은 클래스에서 무조건 정의해야 하는 메서드
    console.log("develop server");
  }
  design(): void {
    console.log("design server");
  }
}

// const dev = new Developer(); // error: cannot create an instance of an abstract class
const josh = new BackEndDeveloper();
const kai = new FrontEndDeveloper();

josh.coding(); // develop server
josh.drink(); // drink sth
josh.design(); // design server

console.log("");

kai.coding(); // develop front
kai.drink(); // drink sth
kai.design(); // design front

export { Developer };

Override is when the class extends another class and replaces the members of its parent.

Class visibility

Class members can be given modifiers that affect visibility:

  • public (default): Allows access to the class member from anywhere
  • private: Only allows access to the class member from within the class
  • protected: Allows access to the class member from itself and any classes that inherit it.

Utility types

Helps with common type manipulations.

  • partial: Changes all properties in an object to be optional.
// 'Partial' example
interface Point {
  x: number;
  y: number;
}

let pointPart: Partial<Point> = {}; // `Partial` allows x and y to be optional
pointPart.x = 10;
  • required: Changes all properties in an object to be required.
// 'Required' example
interface Car {
  make: string;
  model: string;
  mileage?: number;
}

let myCar: Required<Car> = {
  make: 'Ford',
  model: 'Focus',
  mileage: 12000 // `Required` forces mileage to be defined
};
  • record: Shortcut to defining an object type with a specific type and value.
// Record example
const nameAgeMap: Record<string, number> = {
  'Alice': 21,
  'Bob': 25
};

Type aliases

Define an alias of types that get used frequently using type. For example:

type StrOrNum = number | string
let price: StrOrNum

Type assertion (타입 단언)

Asserts a type. This does not affect the runtime and is only inspected while compiling.

This can be used in two different ways:

// Type assertion using angle-brackets
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

// Type assertion using "as"
let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

Interface

The interface declares a new type that can be used to define an object.

The common interface naming convention is to start with "I" then the capitalized variable name. However, the official TS doesn't include starting the variable with an "I" in its naming convention guide.

Creating an interface:

interface IStudent {
	id: number;	
  	name: string;
  	age: number;
}
  • The interface can have a selective property (선택적 프로퍼티) using "?". This specifies a certain property need not exist.
  • A method can also be a property of an interface.
  • The readonly property defines a property cannot be altered after an object is created using the interface.
interface IStudent {
	id: number;	
  	name: string;
  	age?: number;	// The 'age' property is selective
  
  	// Two ways of declaring a method property
  	addSubject?: (subject: string): string;
	addSubject?: (subject: string) => string;

	// Readonly property
	readonly bday: string;
}

Implement the interface to a class

interface CraftBeer {
  beerName: string;
  nameBeer(beer: string): void;
  // test: string;
}

class myBeer implements CraftBeer {
  beerName: string = "Baby Guinness";
  nameBeer(b: string) {
    this.beerName = b;
  }
  constructor() {}
}

Extending the interface (인터페이스 확장)

The interface can be extended similar to a class. The extended interface will have the same properties as the interface extended from.

interface Person {
  name: string;
}

// Extend one interface
interface Developer extends Person {
  skill: string;
}

let fe = {} as Developer;

fe.name = 'josh';
fe.skill = 'TypeScript';

// Or extend multiple interfaces
interface Developer extends Person, Drinker {
  skill: string;
}

let fe = {} as Developer;
fe.name = 'josh';
fe.skill = 'TypeScript';
fe.drink = 'Beer';

Declaring variables and functions

Variables and functions are declared in the following method:

// Variable
let str: string = 'hi'

// Function
function someFunction(input: string):void {}

The colon after the function input defines the return type of the function or no output using void.

The function return type can also be defined in the following method:

// Directly declare the object type
function someFunction(input: string):{
	id: number;	
  	name: string;
  	age: number;
} {}

// Or use an interface
interface ISomeFunctionInput {
	id: number;	
  	name: string;
  	age: number;
}

function someFunction(input: string):someFunctionInput {}

// Return an array of a type
function helloWorld(username: string): string[] {
	return ['Hello', username]
}

// When a parameter is a selective property, you can declare a default parameter (기본 매개 변수)
function helloWorld(username?: string = 'world!'): string[] {
	return ['Hello', username]
}

0개의 댓글