Add generic constraints through extend in TS

interface ILength {
    
    
  length: number
}

function id<Type extends ILength>(value: Type): Type {
    
    
  value.length
  return value
}

console.log(id(['a', 'c']))
console.log(id('abc'))
console.log(id({
    
     length: 10, name: 'jack' }))

explain:

1. Create an interface ILength describing constraints, which requires a length property.
2. Use the interface through the extends keyword to add constraints to generics (type variables).
3. The constraint indicates that the type passed in must have a length attribute.

Note: The actual parameter passed in (for example, an array) only needs to have a length attribute (other types can be used in addition to the length attribute)

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/130051380