Skip to content

Commit 2a6ceb6

Browse files
committed
add constraint example in TS generics
1 parent 0025603 commit 2a6ceb6

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

02-languages/02-apuntes/02-typescript/105 generics.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,15 @@ const compareType = <T, U>(arg1: T, arg2: U): boolean => typeof arg1 === typeof
8383

8484
console.log(compareType<string, number>("1", 1));
8585
console.log(compareType<string, string>("halloween", "halloween"));
86+
87+
88+
// CONSTRAINTS EN GENÉRICOS (Genéricos si, pero no demasiado)
89+
90+
// En muchas ocasiones, queremos la flexibilidad que nos otorgan los genéricos pero
91+
// cumpliendo ciertas limitaciones. Es decir, queremos que el genérico cumpla con
92+
// alguna regla concreta. Para eso tenemos la palabra clave 'extends'.
93+
94+
const getLength = <T extends { length: number }>(input: T): number => input?.length;
95+
96+
console.log(getLength([1, 2, 3]));
97+
console.log(getLength("hello world"));

0 commit comments

Comments
 (0)