let's have function returns type parameterized generic. i'm going using function lot. of time i'll using 1 particular type - number. convenience, nice have alias of function numbers.
toy example:
function arraymaker<t>() : array<t> { return new array<t>(); } let numericalarraymaker: () => array<number> = arraymaker<number>; but typescript compiler complains last line, thinking i'm assigning type number[] numericalarraymaker.
i'm confused why fails, because can assign function (without generic type) variable:
function foo() { return 0; } let foo2 = foo; ... , can assign type (with generic) variable:
type numericalarray = myarray<number>; is there different syntax i'm trying do?
(i understand make example work using factory function returning "arraymakers", becomes deal more verbose, , leads code duplication if function takes arguments.)
all need save reference of arraymaker variable type want:
function arraymaker<t>() : array<t> { return new array<t>(); } let numericalarraymaker: () => array<number> = arraymaker let mynums: number[] = numericalarraymaker(); you can not use generics function signature if you're not calling it, like: arraymaker<number>, makes no real sense.
edit
i'm not sure why compiler doesn't complain about
let numericalarraymaker: (string) => number[] = arraymaker; it might bug, or maybe there's better explanation eludes me, if open issue please post url comment i'd flow on that.
you can go around issue though this:
type arraymaker<t> = (value: t) => t[]; let numericalarraymaker: arraymaker<number> = arraymaker; let mynums: number[] = numericalarraymaker("foo"); // error as why this:
let = arraymaker<number>; doesn't make sense, assigning reference arraymaker function variable a, there's no such thing generics in js there's no meaning arraymaker<number>.
want casting:
let = arraymaker arraymaker<number>; maybe clearer classes:
class a<t> {} let a1 = a<number>; // error let a2 = a<number>; / ok this works with:
type numericalarray = myarray<number>; because here you're dealing type of myarray , not actual function.
this brings else believe in:
don't write code in typescript typescript, if compiled code wrote doesn't anything, written ts compiling, it's bad idea.
i think it's best go with:
let mynums: number[] = arraymaker(4);
Comments
Post a Comment