다형성
type SuperPrint = {
(arr: number[]): void;
(arr: boolean[]): void
(arr: string[]): void
}
let superPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, true, false])
superPrint(['1', '2', '3', '4'])
superPrint(['hi', false, 1])
type DuperPrint = {
<Anithing>(arr: Anithing[]): void
}
let duperPrint: DuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
duperPrint([1, 2, 3, 4])
duperPrint([true, false, true, false])
duperPrint(['1', '2', 3, '4'])
duperPrint(['hi', false, 1])
type SuperDuperPrint = {
<T>(arr: T[]): T
}
let superDuperPrint: SuperDuperPrint = arr => arr[0]
superDuperPrint(['hi', false, 1])
type SuperPrint1 = <T, M>(a: T[], b: M) => T
let superPrint1: SuperPrint1 = (a, b) => {
return a[0]
}
let aa = superPrint1([1, 2, 3, 4], 1)
let bb = superPrint1([true, false, true, false], 1)
let cc = superPrint1(['1', '2', 3, '4'], 1)
let dd = superPrint1(['hi', false, 1], '1')
그래서 보통 어떻게 씀?
type SuperPrint2 = <T>(a: T[]) => T
let superPrint2 = <T>(a: T[]) => {
return a[0]
}
let aaaa = superPrint2<boolean>([1, 2, 3, 4])
let bbbb = superPrint2<boolean>([true, false, true, false])
let cccc = superPrint2(['1', '2', 3, '4'])
let dddd = superPrint2(['hi', false, 1])
type Players<E> = {
name: string
extraInfo: E
}
type favFood = {
favFood: string
}
type PlayerFavFood = Players<favFood>
const Jaejun: PlayerFavFood = {
name: "jaejun",
extraInfo: {
favFood: "kimchi"
}
}
const Taehwan: Players<null> = {
name: "Taehwan",
extraInfo: null
}
type A = Array<number>
function printAllNumbers(arr: A) {
return arr
}
function printAllNumbers1(arr: Array<number>) {
return arr
}
function printAllNumbers2(arr: number[]) {
return arr
}
배움출처: https://nomadcoders.co/typescript-for-beginners/lobby