Reputation:
I'm writing a constructor that takes a string, and int and a function (and possibly something more that I'm not aware of at the moment). This far, I've got the following.
export class Blobb {
constructor(public value: number,
public name: string,
public mapping: function,
public misc: any) { ... }
}
Apparently, the variable mapping
crashes the transpilation because function isn't a valid type. I'm not sure what to do with it.
Is there a specific type for a function being passed to the constructor? Is any
the preferred approach? Should I consider declaring my own type?
If it's of any significance, the function to be passed will always be something like this (but with varying computations, of course).
mapping() {
this.value * 13 + ": " + this.name;
}
Upvotes: 0
Views: 127
Reputation: 40642
You can annotate the parameter with the exact function signature instead of specifying it just as a Function
. In your case it can be typed as () => void
:
export class Blobb {
constructor(public value: number,
public name: string,
public mapping: () => void,
public misc: any) { ... }
}
TypeScript function types: https://www.typescriptlang.org/docs/handbook/functions.html#function-types
Upvotes: 2
Reputation: 31
I think you need Function
with an uppercase 'F' instead of function
.
function
is the key word to declare a new function I believe.
Upvotes: 0
Reputation: 61
You could use the interface 'Function' in es2015 or above, so it could look like,
export class Blobb {
constructor(public value: number,
public name: string,
public mapping: Function,
public misc: any) { ... }
}
Upvotes: 0
Reputation: 5156
I have not used them myself but from the documents, I see that Type Aliases are a thing (Introduced in TS 1.4);
e.g.:
type NameResolver = () => string;
function getName(n: NameOrResolver): Name {...}
Upvotes: 1