Open mfulton26 opened 3 years ago
Why would you do it this way instead of Array[Symbol.species]
, though?
e.g. a custom map
function or any function that receives an array and wants to honor the Symbol.species]
property of the incoming array to return an array of possibly the same type
declare function map<T, R>(array: T[], mapper: (value: T) => R): R[];
here you wouldn't want to statically reference Array
but dynamically get the constructor for the incoming array
and here's a more concrete, non-array example: creating a map
function for Set
(same could go for Map
)
export default function map<T, R>(
this: Set<T>,
mapper: (value: T) => R
): Set<R> {
const result = new (<SetConstructor>this.constructor)[Symbol.species]<R>();
for (const value of this) {
result.add(mapper(value));
}
return result;
}
I think the cast shouldn't be needed but currently is
lib Update Request
Configuration Check
My compilation target is
ES2015
and my lib isthe default
.Missing / Incorrect Definition
Array
and other interfaces for built-ins do not declare their ownconstructor
methodsSample Code
The code compiles fine when defining the appropriate
constructor
method:Playground link
Documentation Link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor