node.js Typescript project, key-value pair - node.js

So I try to create a value pair type and get the error message: "Cannot find name 'key'."
How does it work properly?
import * as websocket from "websocket";
let wsClientsList: {[key: string]: websocket.connection};
for(key in wsClientsList){
// ^^^ TS2304: Cannot find name 'key'.
wsClientsList[key].sendUTF(message);
console.log('send Message to: ', wsClientsList[key]);
}

You need to declare a variable named key using var, let or const
for(let key in wsClientsList) {
wsClientsList[key].sendUTF(message);
console.log('send Message to: ', wsClientsList[key]);
}
You can use const in most cases in for in and for of loops, unlike in traditional for loops with increment.

Related

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

How do I extend the Error class?

This is my code:
let errorBadRequest = new Error("Bad request");
res.statusCode = 400;
errorBadRequest.errors = err.details.reduce(function(prev, current) {
prev[current.path] = current.message;
return prev;
}, {});
throw errorBadRequest;
I wanted to extend error attribute in error instance, but tsc said joi-utils.ts(21,23): error TS2339: Property 'errors' does not exist on type 'Error'.
The structure of errors is {fieldname: fieldmsg}, it's according to my joi request schema to decide.
How do I solve the error from typescript compiler? I think I need to declare a interface and be designate the attribute.
Property 'errors' does not exist on type 'Error'.
Create a file called error-extension.d.ts and have the following:
interface Error {
errors: Error;
}
More : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html
I find when initialing the Error class, actually it hasn't errors in Error . It should make a interface and set errors to option.
This is my solution:
interface IJoiErrorException extends NodeJS.ErrnoException {
errors?: Object;
}
const errorBadRequest: IJoiErrorException = new Error("Bad request");

Error handling in Node.js for calling a function with wrong name

I am requiring a module and saving it in a variable. But when I call a module function by wrong name, it does not throw any error or consoles any error. How do I make this throw error?
var module = require('../pre_process/' + preProcessFolder + '/' + preProcessModule);
// module -> { XYZ: [Function] }
//Following does not throw error and doesn't console anything.How to handle/debug this error
module['XY'](result, userId)
.then(function(recData) {
})
I am using q library for promise.
So you want to check if a function (provided by a modul) exists.
You could use try like the example here:
Javascript check if function exists

Resources