Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

typescript generics constraints

// Restrict your generic type by using keyword extends
interface Length = {
  length: number;
};

function getLength<T extends Length>(arg: T) {
  return arg.length
}

getLength("Hi there!") // success
getLength([1,2,3]) // success
getLength(undefined) // error
getLength(67) // error
 
PREVIOUS NEXT
Tagged: #typescript #generics #constraints
ADD COMMENT
Topic
Name
2+1 =