typescript generic

BackEnd_Ash.log·2021년 8월 8일
0

typescript

목록 보기
8/17

https://hyunseob.github.io/2017/01/14/typescript-generic/
https://www.typescriptlang.org/docs/handbook/2/generics.html

📌 object

function object_merge<A, B>(a: A, b: B): A & B {
  return {
    ...a,
    ...b
  };
}

const merged1 = object_merge({ foo1: 1 }, { bar1: 1 });
console.log(merged1); // { foo1: 1, bar1: 1 }

const merged2 = object_merge({ food: "string1" }, { food2: "string2" });
console.log(merged2); // { food: 'string1', food2: 'string2' }

📌 list

i wanted to use the concat method, error has occured

parameters A and B are generic, but the return type is string[] , so the types may not overlap.

there are no restrictions on generics A and B, so you can use number[] as well as string[] , and the return type will not match.

you'll have to bind the return type together as a generic or add a constraint to the generic argument.

function list_merge1<A>(a:Array<A>, b:Array<A>): Array<A> {
	return a.concat(b);
}
function list_merge2<A extends string[], B extends string[]>(a: A, b: B): string[] {
	return a.concat(b);
}

const merged3 = list_merge1(["1"], ["string1", "string2", "string3"])
console.log(merged3);

const merged4 = list_merge2([1], ["string1", "string2", "string3"])
console.log(merged4);
profile
꾸준함이란 ... ?

0개의 댓글