Property 'ensure' does not exist on type 'NodeRequire' - node.js

I'm trying webpack 2 code splitting.
According to this doc: https://webpack.js.org/guides/code-splitting-require/
the following code should include some.css into a new chunk named 'something'
require.ensure([], function(require) {
require('some.css');
}, 'something');
but when I run it, I get this error:
ERROR in ./src/index.ts
(4,9): error TS2339: Property 'ensure' does not exist on type 'NodeRequire'.
Any idea about how to fix it?
Thanks

The way I solved this was by creating my own interface - WebpackRequire - which extends NodeRequire with ensure1.
interface WebpackRequire extends NodeRequire {
ensure(
dependencies: string[],
callback: (require: WebpackRequire) => void,
errorCallback?: (error: Error) => void,
chunkName?: string
): void;
};
If you've only got a single instance of require.ensure, you can then type cast it to a WebpackRequire using (require as WebpackRequire).ensure, but since I used it multiple times in a module, I created local require at the top scope of the module, type cast as WebpackRequire, like this:
const require: WebpackRequire = (window as any).require;
1I got the types of ensure from the Webpack docs

I required a javascript document which then did the require. Not exactly the nicest solution, but it did work

Related

Unable to perform update on my question in SPFX. Uncaught (in promise) Error: Error making HttpClient request in queryable [400] odata.error

I have fixed this issue on one of my earlier projects but it seems like I am unable to do it on this project and I don't know why.
The fix that I have done earlier was by adding delete updateFAQ["odata.metadata"]
Though the error vscode gives now is the following:
Element implicitly has an 'any' type because expression of type '"odata.metadata"' can't be used to index type 'IFAQ. Property 'odata.metadata' does not exist on type 'IFAQ'
For context the method looks like this:
public async updateFAQ(updateFAQ: IFAQ): Promise<void> {
delete updateFAQ["odata.metadata"] //vscode gives an error
await this._sp.web.lists.getById(this.faqListId).items.getById(updateFAQ.ID).update(updateFAQ);
}
Can someone give some guidance on why the error occurs and why delete updateFAQ["odata.metadata"] gives an error?
If there is anything that you need context to just say the word.
The full error in the console looks like this: Uncaught (in promise) Error: Error making HttpClient request in queryable [400] ::> {"odata.error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"A relative URI value 'Web/Lists(guid'e6197c8f-88c1-47c4-911e-538ee0638250')/Items(25)' was specified in the payload, but the odata.metadata annotation is missing from the payload. The payload must only contain absolute URIs or the odata.metadata annotation must be on the payload."}}} at HttpRequestError.init (parsers.js:96:1) at async Proxy.errorCheck (parsers.js:45:1) at async queryable.js:118:1
EDIT: Interface
export interface IFAQ {
ID?: number;
Question: string;
Answer: string;
}
UPDATE/SOLUTION
I've got it fixed. What I did was by mapping the result sp.web.lists into an object called finalResultwhere I set the object properties to the properties of the IFAQ. Then I return finalResult. In that way I choose that I only want to return the properties of the IFAQ and not any metadata or odata:
public async getFAQ(): Promise<IFAQ[]> {
let result: IFAQ[] = await this._sp.web.lists.getById(this.faqListId).items();
let finalReuslt = result.map((x) => ({
ID: x.ID,
Question: x.Question,
Answer: x.Answer
}))
return result;
}

Ambiguos "Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type" error in nexus graphql

I'm getting the following error when using nexus to define a graphql schema with apollo-server.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type
The stacktrace doesn't give much information as to where the issue is occurring or to what the problem is. The project has 20+ models and dozens of resolvers so it's quite hard to debug.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type, check the docs for extending types
at extendError (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1744:2)
at SchemaBuilder.addType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:603:8)
at SchemaBuilder.missingType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1212:5)
at SchemaBuilder.getOrBuildType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1540:4)
at SchemaBuilder.getOutputType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1471:10)
at SchemaBuilder.buildOutputField (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1349:52)
at /Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1307:7
at Array.forEach (<anonymous>)
at SchemaBuilder.buildOutputFields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1306:7)
at fields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1009:33)
Any help appreciated.
I got the same error, but it was because I removed some exports. I'm not exactly sure what caused it, but I basically have a file that exports all of my graphql modules. E.g.
// graphql/modules/index.ts
export * from './file-a';
export * from './file-b';
When I removed the second export line, I started getting the error. I'm probably using some of the types defined in file-b somewhere else, and that's somehow causing the error. Anyway, adding the line back in fixed it (I had removed it by accident anyway).
UPDATE
I also go this by referencing some arg types that didn't exist (typo). For example:
args: {
where: arg({ type: 'ConversationsWhereInput' }),
orderBy: arg({ type: 'ConversationsOrderByInput', list: true }),
},
The s in Conversations shouldn't be there. It should be:
args: {
where: arg({ type: 'ConversationWhereInput' }),
orderBy: arg({ type: 'ConversationOrderByInput', list: true }),
},
It could have been much helpful if you could elaborate what did you do before this error happened.
I just came up with this error exactly as same as what you got and for me it was because I just accidentally changed the name for objectType of typeDef.
For instance, the name for the FollowUserResult was actually FollowResult and after I changed the name, the whole mutation resolvers related to this objectType became wrong.
export const FollowUserResult = objectType({
name: "FollowUserResult", // It was originally "FollowResult"
definition(t) {
t.nonNull.boolean("ok");
t.string("error");
},
});
You may check on this again. Once you got those correct, delete the schema.graphql file and generate the new schema.graphql file.
I got this error because I was using the incorrect Node version. My project didn't have a .nvrmc file (yet) so I was using Node 10 on a project that uses Node 14. So after switching to the correct Node version this error went away
I got this error when I incorrectly specified an unknown type in the type attribute of an extension to the Query type. More specifically:
export const CoursesQuery = extendType({
type: "Query",
definition(t) {
t.field("myQuery", {
type: InvalidType, // <--- Changing InvalidType to the correct type fixed the error
async resolve(_parent, _args, ctx) {
return ...
},
});
},
});
The error disappeared after I changed InvalidType to the correct type and restarted the server.

Jest error with <Trans>: You forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

Error: Uncaught [Error: Element type is invalid: expected a string
(for built-in components) or a class/function (for composite
components) but got: undefined. You likely forgot to export your
component from the file it's defined in, or you might have mixed up
default and named imports.
This is the error I was getting while running test in jest. React component which is being tested uses <Trans> from react-i18next. When I comment that portion of code, test were working as expected.
The error shown is very very very miss leading.
In my case it was missing mock for <Trans>. While I had mock for react-i18next, but since I had many components to cover with tests, and some of them were using <Trans> and some of them not, I copy/paste test files but totally forgot to check about mock. It took me few hours to notice it, after I replaced <Trans> to text like <Typography> from material-ui...
jest.mock('react-i18next', () => ({
withTranslation: () => (Component: any) => {
Component.defaultProps = {...Component.defaultProps, t: (children: any) => children};
return Component;
},
Trans: ({children}: any) => children, // this line was missing (() => jest.fn() might also work)
}));
Hope it will save some time for some of you :)
I faced the same issue, in order to resolve the issue I mocked the Trans component like this
jest.mock("react-i18next", () => ({
Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey,
}));
Instead of passing the node, we can simply pass the i18nKey.
In my case, I am only checking the key value. Hope it helps!

Assign custom methods in mongoose .d.ts so I can use them anywhere with mongoose in typescript

I am trying to create a custom function in mongoose Api hooks but the function is not defined as it has not declared. I have created index.d.ts separate file but don't know how to add that.
const exec = mongoose.Query.prototype.exec;
mongoose.Query.prototype.cache = function (options:ICacheOptions = {}) {
this.useCache = true;
this.hashKey = JSON.stringify(options.key || "");
return this;
}
link :: cache.ts!
error is: Property 'cache' does not exist on type 'Query'. Did you mean 'catch'?
what I have tried: I created .d.ts file and try to declare them.
declare module 'mongoose' {
interface DocumentQuery<T, DocType extends import("mongoose").Document, QueryHelpers = {}>{
mongooseCollection: {
name: any;
};
cache():DocumentQuery<T[], Document> & QueryHelpers;
useCache: boolean;
hashKey: string;
}
}
link:: index.d.ts!
My Errors are ::
src/lib/services/cache.ts(16,26): error TS2551: Property 'cache' does not exist on type 'Query<any>'. Did you mean 'catch'?
src/lib/services/cache.ts(17,8): error TS2339: Property 'useCache' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(18,8): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(25,12): error TS2339: Property 'useCache' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(30,41): error TS2339: Property 'mongooseCollection' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(33,52): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(45,22): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(46,24): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
I want somehow I can fix this and also want to know how can I extend some property in .d.ts if they are class. Thanks in advance.
Your augmentation does work. It needs to be placed somewhere that you have configured TypeScript to look for source files. The declare module style of type definition is called an "ambient declaration" which means that you don't have to put it in any particular directory or file. It can even be in a regular .ts file. The easiest thing to do is to put the declaration in cache.ts, the same file where you assign mongoose.Query.prototype.cache.
Edit: I forgot to address your specific question about augmenting a class. As you guessed you can augment a class by using the interface keyword. That is because in TypeScript defining a class does two things: it defines a value (the constructor function that is invoked when you call, e.g., new DocumentQuery), and a type for instances of the class which is really an interface. The value and the type both have the same name. Because the type part of a class is an interface you can augment it like any other interface.
So in this case you augment the DocumentQuery type, which is the superclass of Query, but you assign the cache method to the Query prototype. That works because Query extends DocumentQuery, so when you declare that DocumentQuery now has a cache method TypeScript assumes that subclasses, including Query, have the same method. This does lead to a discrepancy: TypeScript now assumes that DocumentQuery instances have a cache method, but you only really defined that method for Query. It would be more accurate to either change your type declaration to augment Query instead of DocumentQuery, or to assign the method implementation to DocumentQuery.prototype instead of to Query.prototype.

How can I extend Node's stream

I'm trying to create a method for Readable Stream, but after trying just a little bit, I ran out of ideas to how.
import * as stream from 'stream'
//yields Property 'asdasas' does not exists on type 'Readable'
stream.Readable.prototype.asdasas
//yields asdas does not exists on type 'typeof Readable'
stream.Readable.asdas
Can someone give me a solution and explain why the errors happened? Thanks
explain why the errors happened
The first rule of migrating from JavaScript to TypeScript:
Declare what you use.
https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html
Here Readable doesn't have the member you are looking for. If you want to add it, you need to declare it. Something like :
interface Readable {
asdfasdfasdf: any;
}
I managed to extend them. The behaviour wasn't as unusual as I thought (I still would appreciate an explanation on the difference of "type 'Readable'" and "type 'typeof Readable'". The code:
import * as stream from 'stream'
class mod_Readable extends stream.Readable {
pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T {
//whatever
return super.pipe(destination, options)
}
}

Resources