Issue
I have a TypeScript project which takes advantage of Object.groupBy
. Sadly, my TypeScript compiler doesn't know that what means.
Object.groupBy(collection, ({ foo }) => foo);
// ts(2339) Property 'groupBy' does not exist on type 'ObjectConstructor'
Since I'm naive and full of dreams, I figured that I could simply create my own definition file to sort that out.
// lib/lib.object-groupby.d.ts
export {}
declare global {
interface ObjectConstructor {
/**
* Groups the given objects by a key taken from the object values.
* @param items Items to group.
* @param callbackFn Function identifying the key for the groups.
*/
groupBy<T, K extends PropertyKey>(
items: T[],
callbackFn: (element: T, index: number) => K
): Record<K, T[]>;
}
}
My problem is that I can't work out how to add it to tsconfig.json
. Whenever I try to add it so that I can compile the project using gulp-typescript, I keep seeing the same error.
I tried adding it to the files
property, but that didn't seem to work.
{
"files": ["./assets/lib/lib.object-groupby.d.ts"]
}
I tried adding it to typeRoots
, with no success again.
{
"typeRoots": ["./node_modules/@types", "./assets/lib/lib.object-groupby.d.ts"]
}
How do I add the file so that my project will compile?
Solution
I'm going to add the solution that I ended up going with that works with Gulp and VSCode. Hopefully this will help someone else in the same frustrating situation.
For starters, here's a simplified view of my folder structure.
app/
├── assets/
│ ├── ts/
│ │ ├── lib/
│ │ │ └── lib.object-groupby.d.ts
│ │ ├── index.ts
│ │ ├── index.d.ts
The lib.object-groupby.d.ts
file had the definition itself. Just including this file seems to be enough for VSCode to be happy.
// assets/ts/lib/lib.object.groupby.d.ts
export {}
declare global {
interface ObjectConstructor {
/**
* Groups the given objects by a key taken from the object values.
* @param items Items to group.
* @param callbackFn Function identifying the key for the groups.
*/
groupBy<T, K extends PropertyKey>(
items: T[],
callbackFn: (element: T, index: number) => K
): Record<K, T[]>;
}
}
I needed to create an index.d.ts
file in the root that imports that definition. This allows gulp-typescript to understand and include the file.
// assets/ts/index.d.ts
import "./lib/lib.object-groupby";
The tsconfig.json
file didn't need anything special to be added, everything just kinda worked.
Answered By - James Long
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.