TS2345: Argument of type X is not assignable to parameter of type Y - node.js

Weird error with TypeScript:
As the image indicates, the error is:
TS2345: Argument of type 'ErrnoException' is not assignable to
parameter of type '(err: ErrnoException) => void'. Type
'ErrnoException' provides no match for the signature '(err:
ErrnoException): void'.
Here is the code that causes the error:
export const bump = function(cb: ErrnoException){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};
Anybody know what's going on here?

You are sending a value with the type ErrnoException, while the function you are calling expects a function that takes a parameter of type *ErrnoException** and returns void.
You send:
let x = new ErrnoException;
While the function you call expects
let cb = function(e: ErrnoException) {};
You can change your function to receive the correct parameter like this.
export const bump = function(cb: (err: ErrnoException) => void){
const {pkg, pkgPath} = syncSetup();
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};

Related

Write openpgp.encrypt stream to S3 not working

I'm trying to push the stream from openpgp.encrypt to an S3 bucket.
Typescript reports const encrypted: openpgp.WebStream<Uint8Array> though it should probably be NodeStream as I'm using nodejs v18 within an AWS Lambda. I'm using openpgpjs v5.5.0.
const publicKeyArmored = settings.publicKey
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored })
const cleartextStream = getS3InputStream({ bucket, objectKey })
const message = await openpgp.createMessage({
text: cleartextStream,
format: 'binary'
})
const encrypted = await openpgp.encrypt({
message,
format: 'binary',
encryptionKeys: publicKey,
config: {
preferredCompressionAlgorithm: openpgp.enums.compression.uncompressed
}
})
const { s3Outstream: ws, s3Promise } = createS3OutputStream(bucket, outKey)
await pipeline(
encrypted,
ws
)
await s3Promise // wait for upload to finish
Typescript errors
No overload matches this call.
Overload 1 of 7, '(source: PipelineSource<any>, destination: PassThrough, options?: PipelineOptions | undefined): Promise<void>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'PipelineSource<any>'.
Overload 2 of 7, '(streams: readonly (WritableStream | ReadableStream | ReadWriteStream)[], options?: PipelineOptions | undefined): Promise<...>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'readonly (WritableStream | ReadableStream | ReadWriteStream)[]'.
Type 'WebStream<Uint8Array>' is missing the following properties from type 'readonly (WritableStream | ReadableStream | ReadWriteStream)[]': length, concat, join, slice, and 18 more.
Overload 3 of 7, '(stream1: ReadableStream, stream2: WritableStream | ReadWriteStream, ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]): Promise<...>', gave the following error.
Argument of type 'WebStream<Uint8Array>' is not assignable to parameter of type 'ReadableStream'.
Type 'WebStream<Uint8Array>' is missing the following properties from type 'ReadableStream': readable, read, setEncoding, pause, and 22 more.ts(2769)

RxJS Http Server with typescript compile errors

I'm pretty newbie with rxjs, can you please tell what's wrong with below?
interface IHTTP {
req: IncomingMessage;
res: ServerResponse;
handler?: Promise<any>;
}
server = http.createServer();
let request$: Observable<any>;
request$ = fromEvent(server, 'request').pipe(
map(([req, res]: [IncomingMessage, ServerResponse]): IHTTP => {
return { req, res } as IHTTP;
}
)
);
Compile error:
TS2345: Argument of type 'OperatorFunction<[IncomingMessage, ServerResponse], IHTTP>' is not assignable to parameter of type 'OperatorFunction<unknown, IHTTP>'.   Type 'unknown' is not assignable to type '[IncomingMessage, ServerResponse]'.
I found the problem I had to define fromEvent's first argument as:
server as FromEventTarget<[http.IncomingMessage, http.ServerResponse]>
Otherwise Typescript thinks it's FromEventTarget<unknown>

TypeScript - Type undefined is not assignable to type ICustomType

I'm quite new to TypeScript and trying to understand what is the best way to approach such situation in my code.
I have array of objects that have a custom type in my system and I use Array.find method to get one of them. However I receive a compile error saying Type 'undefined' is not assignable to type IConfig.
Here's the code example -
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
// Type 'undefined' is not assignable to type IConfig
I tried to add undefined as possible type but then I get error on the next line which uses this object Object is possibly 'undefined', e.g. -
const config: IConfig | undefined = CONFIGS.find(({ code }) => code === 'default');
// Object is possibly 'undefined'
if (config.foo) {
return 'bar';
}
What is the best way to approach such type issues?
.find will return undefined if nothing in the array passes the callback test. If you're sure that default code exists in the array, then use the non-null assertion operator:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default')!;
// ^
(If you weren't sure if it exists in the array, the warning you see is there to prompt you to explicitly test for if the item exists before trying to access a property on it, otherwise you'll sometimes get a runtime error:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
if (!config) {
return 'No match found';
}
if (config.foo) {
return 'bar';
}
)

Argument of type '{}' is not assignable to parameter of type 'Uint8Array'

I'm trying to clone and run an opensource project repo and having hard time fixing this issue, npm start fails with "compile failed error' and its states the following reason.
Argument of type '{}' is not assignable to parameter of type 'Uint8Array'
const [encChallenge] = await waitEvent(socket, 'data')
const challenge = decrypt(encChallenge) //This line causes the error
Following in the decrypt function
/** Decrypt data used shared key */
function decrypt(data: Uint8Array) {
if (!sharedKey) return null
const nonce = data.slice(0, sodium.crypto_box_NONCEBYTES)
const box = data.slice(sodium.crypto_box_NONCEBYTES, data.length)
const msg = crypto.decrypt(box, nonce, sharedKey)
return msg
}
Changing the parameter to any solves it but I can't do that,
How can I convert my parameter to Unit8Array?
As long as encChallenge is a typed array represents an array of 8-bit unsigned integers then you should just be able to do:
const [encChallenge] = await waitEvent(socket, 'data')
const challenge = decrypt(new Uint8Array(encChallenge);)
really i would make waitEvent encChallenge be of strongly type Uint8Array in waitEvent method, then it's abstracted away and always that type if you reuse it again.

Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'

new to Typescript. I am reading some data from RabbitMQ channel and am converting it to JSON object. In this line I get the error
let communicationInformation = JSON.parse(newCommunication.content);
TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.
Do I need to cast the data? I am using Typescript 2.4.1
Amqplib.connect(amqpLibUrl, (err, connection) => {
if (!err) {
connection.createChannel((err, channel) => {
channel.consume('QueueName', newCommunication => {
if (newCommunication != null) {
let communicationInformation = JSON.parse(newCommunication.content);
// Code
}
})
})
}
});
I think the error is thrown on the input parameter of JSON.parse. Try to first call toString on it then pass to the function.
let communicationInformation = JSON.parse(newCommunication.content.toString());
I am not sure what is newCommunication.content. In my case it is a file and I had to specify encoding for fs.readFileSync:
const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));
Next Error was error TS2531: Object is possibly 'null'.
You have to disable strictNullChecks in your compiler

Resources