📘

【Typescript】メモ✍

2021/05/01に公開

基本的な型

const word: string = "hello";
const bool: boolean = true;

type Name = {
  firstName: string;
  lastName: string;
}
const userInfo: Name = {
  firstName: "foo";
  lastName: "bar";
}

const myFunc = (x: number, y: number): string => {
  const result = x + y;
  return result.toString();
}

Intersection Types

type GROUP = {
  groupName: "string";
}
type PROFILE = {
  name: string;
  position: string;
}
type MEMBER = GROUP & PROFILE;

const memberA: MEMBER = {
  groupName: 'ITZY',
  name: 'RYUJIN',
  position: 'main rapper'
}

Union Types

let value: boolean | number;
value = true;
value = 10;
value = "hello" // error

let arrayUni: (number | string)[];
array1 = [0, 1, 2, "hello"];
array1 = [0, 1, 2, true]; // error

Literal Types

let member: 'Jennie' | 'Rose' | 'Lisa' | 'Jisoo' = 'Jennie';
member = 'black pink' // error

typeof

let message: string = 'Hi';
let message2: typeof msg;
msg2 = 'hello';
msg2 = 1 // error

let artist = {name: 'Aimer'};
let album: typeof artist = {name: 'Walpurgis'};

keyof

type KEYS = {
 primary: string;
 secondary: string;
};
let key: keyof KEYS;
key = 'primary' // or 'secondary'

// typeof + keyof
const JPOP = {
 utada: 'One Last Kiss';
 milet: 'checkmate';
}
let keySports: keyof typeof JPOP;
keySports = 'utada'; // or 'milet'

enum

enum OS {
 Windows,
 Mac,
 Linux,
}
interface PC {
  id: number;
  OSType: OS;
}
const PC1: PC = {
 id: 1,
 PsType: OS.Windows,
};
const PC2: PC = {
 id: 2,
 PsType: OS.Mac,
};

型の互換性

const comp1 = 'test';
let comp2: string = comp1;

let comp3: string = 'test';
let comp4: 'test' = comp3; // error

let functComp1 = (x: number) => {}
let functComp2 = (x: string) => {}

functComp1 = functComp2 // error
functComp2 = functComp1 // error

Generics ジェネリックス

interface GEN<T> {
    item: T;
}
const gen0: GEN<string> = {item: 'hello'}
const gen1: GEN = {item: 'hello'} // error
const gen2: GEN<number> = {item: 100}

interface GEN1<T = string> {
    item: T;
}
const gen3: GEN1 = {item: 'hello'}

interface GEN2<T extends string | number> {
    item: T
}
const gen4: GEN2<string> = {item: 'hello'}
const gen5: GEN2<number> = {item: 100}
const gen6: GEN2<boolean> = {item: true} // error

function funcGen<T>(props: T) {
    return {item: props}
}
const gen7 = funcGen('test');
const gen8 = funcGen<string | null>(null);

function funcGen1<T extends string | null> (props: T) {
    return {value: props}
}
const gen9 = funcGen1('hello')
const gen10 = funcGen1(100) // error

interface Props {
    price: number;
}
function funcGen3<T extends Props>(props: T) {
    return {value: props}
}
const gen11 = funcGen3({price: 1000})

// arrow function
const funcGen4 = <T extends Props>(props: T) => {
    return {value: props}
}

Discussion