I have an interface that looks like that:
interface Person {
name: string;
age: number;
group: Options
}
and an enum that looks like this:
export enum Options {
ONE = 'one',
TWO = 'two',
THREE = 'three',
}
I want to create a new object where the key will be one of the Options and the value will be Person.
I tried something like that:
type PersonMapped = {
[key in Options]: Person; // error on the in keyword
}
But I get an error that says: parsing error: Unexpected token, expected "]".
What's wrong with this code?
Edit 1:
Here's the code example that I try to use:
export enum Group {
ONE = 1,
TWO = 2,
THREE = 3
}
export type Mappable = {
[key in Group]: string
}
Here's the error from the ide:
Edit 2:
It seems that the problem is with my editor settings. I'm using vscode version - 1.59.1. I also have eslint extension installed with version - 2.1.23.
Related
This is a follow up on this question. Now I am using the point object correctly however I get this error:
src/actions/collectGpsData.ts:22:43 - error TS2322: Type '{ type: string; coordinates: any[]; }' is not assignable to type 'GeometryDataType'.
Object literal may only specify known properties, and '"coordinates"' does not exist in type 'GeometryDataType'.
22 place.location = { "type": "Point", "coordinates": [point.latitude, point.longitude] };
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.
import { Action } from "actionhero"; // No GeometryDataType sequelize.js definition
import { Place } from "../models/Place";
export class CollectGpsData extends Action {
constructor() {
super();
this.name = "collectGpsData";
this.description = "Collects GPS data and inserts it into the database";
this.outputExample = {};
this.inputs = {
gpsdata: {
required:true
}
}
}
async run(data) {
var GPSdata = data.params.gpsdata;
GPSdata.forEach(point => {
var place = new Place();
place.deviceimei = point.deviceimei;
place.location = { "type": "Point", "coordinates": [point.latitude, point.longitude] }; //error line
});
}
}
Why am I getting this error? and how can I avoid this error in the future?
I've answered it in your GitHub issue:
Hello #krlicmuhamed!
As #nainkunal933 noted, please include a complete code sample next time. The code you posted does not show how User is defined, for example. Please use a sequelize-sscce.
That said, I took the time to look into what's happening and tried to figure it out.
So, first of all, this issue is typescript-only. The code works fine in runtime. Please include this information directly next time.
I ventured into your stackoverflow question and comments and found this:
https://gist.github.com/krlicmuhamed/199c0bc3560a08718b553f3f609acbcd#file-places-ts-L22
Did you find any documentation instructing you to use this specific type explicitly here? If yes, please post the link so I can fix it. Regardless, I don't blame you because we really should have a set of recommended types to apply on each data type. It turns out GeometryDataType is not the correct type to use in this case.
The solution is to install #types/geojson:
npm install --save-dev #types/geojson
Then, import Geometry:
import type { Geometry } from '#types/geojson'
And then replace that line of code in which you put GeometryDataType with Geometry:
#AllowNull(false)
#Column(DataTypes.GEOMETRY)
- location: GeometryDataType;
+ location: Geometry;
Problem statement
I've got problem with an object array I would like to get a sub object array from based on a object property. But via the Array.filter(lambda{}) all I get is an empty list.
The object is like:
export interface objectType1 {
someName: number;
someOtherName: string;
}
export interface ObjectType2 {
name: string;
other: string;
ObjectType1: [];
}
The method to get the subArray is:
private getSubArray(toDivied: ObjectType2[], propertyValue: string){
let list: ObjectType2[] = toDivied.filter((row:ObjectType2) => {
row.name === propertyValue
});
return list;
}
Analys
Namely two things been done ensure filter comparing works and that the data is "as expected".
Brekepoints in visual studio code
Via break points in the return and filter compareison I've inspected that the property value exists (by conditions on the break point) and that the "list" which is returned is empty.
I would like to point out that I use a Typescript linter which usally gives warning for the wrong types and undefined variable calls and such so I am quite sure it shouldn't be an syntax problem.
Tested via javascript if it works in chrome console
remove braces inside callback function
private getSubArray(toDivied: ObjectType2[], propertyValue: string){
let list: ObjectType2[] = toDivied.filter((row:ObjectType2) =>
row.name === propertyValue
);
return list;
}
I have a config file. It has variables stored in the following manner.
[general]
webapp=/var/www
data=/home/data
[env]
WEBAPP_DEPLOY=${general:webapp}/storage/deploy
SYSTEM_DEPLOY=${general:data}/deploy
As you can see it has 2 sections general and env. Section env uses the variables from section general.
So I want to read this file into a variable. Let's say config. Here's I want config object to look like:
{
general: {
webapp: '/var/www',
data: '/home/data'
},
env: {
WEBAPP_DEPLOY: '/var/www/storage/deploy',
SYSTEM_DEPLOY: '/home/data/deploy'
}
}
I general I am looking for a config parser for nodejs that supports string interpolation.
I would assume most ini libraries don't include the variable expansion functionality, but with lodash primitives a generic "deep object replacer" isn't too complex.
I've switched the : delimiter for . so has and get can lookup values directly.
const { get, has, isPlainObject, reduce } = require('lodash')
// Match all tokens like `${a.b}` and capture the variable path inside the parens
const re_token = /\${([\w$][\w\.$]*?)}/g
// If a string includes a token and the token exists in the object, replace it
function tokenReplace(value, key, object){
if (!value || !value.replace) return value
return value.replace(re_token, (match_string, token_path) => {
if (has(object, token_path)) return get(object, token_path)
return match_string
})
}
// Deep clone any plain objects and strings, replacing tokens
function plainObjectReplacer(node, object = node){
return reduce(node, (result, value, key) => {
result[key] = (isPlainObject(value))
? plainObjectReplacer(value, object)
: tokenReplace(value, key, object)
return result
}, {})
}
> plainObjectReplacer({ a: { b: { c: 1 }}, d: 'wat', e: '${d}${a.b.c}' })
{ a: { b: { c: 1 } }, d: 'wat', e: 'wat1' }
You'll find most config management tools (like ansible) can do this sort of variable expansion for you before app runtime, at deployment.
Using grpc with Node, Enums in responses to my queries are resolving as integer values. However, when I make the same queries with BloomRPC, the Enums resolve as Integer values.
Is there a parameter or option to force these Enums to be resolved as String using Node grpc?
In our project, we use enum to help us ensure the integrity of a finite set of possibilities by eliminating human error. Why should we need to remember what the string value is when we have the protocol buffer enum so handy? Thus, we use the .proto as the source of truth; that's our rule.
To do that, follow these steps, which are written for ES6+ code.
Define your gRPC/Protobuf enum in a .proto file.
// life.proto
syntax = 'proto3';
package life;
enum Choices
{
EAT = 0;
DRINK = 1;
SLEEP = 2;
CODE = 3;
SKI = 4;
}
Install #grpc/proto-loader and #grpc/grpc-js.
$ npm i -s #grpc/proto-loader #grpc/grpc-js
Import the modules that pay the bills, so to speak. Load the .proto file directly into memory (don't compile).
// myNodeApp.js
import * as grpc from '#grpc/grpc-js'
import * as protoLoader from '#grpc/proto-loader'
import path from 'path'
// these options help make definitions usable in our code
const protoOptions = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
}
// this allows us to prepare the path to the current dir
const dir = path.dirname(new URL(import.meta.url).pathname)
// this loads the .proto file
const lifeDef = protoLoader.loadSync(path.join(dir, 'life.proto'), protoOptions)
// this loads the package 'life' from the .proto file
const life = grpc.loadPackageDefinition(lifeDef).life
Take a peek at the enum Choices definition (in the same file).
// myNodeApp.js (cont'd)
console.log(life.Choices)
/* stdout */
{
format: 'Protocol Buffer 3 EnumDescriptorProto',
type: {
value: [ [Object], [Object], [Object], [Object], [Object] ],
name: 'Choices',
options: null
},
fileDescriptorProtos: [
<Buffer 0a ... 328 more bytes>
]
}
...look deeper...
console.log(life.Choices.value)
/* stdout */
{
value: [
{ name: 'EAT', number: 0, options: null },
{ name: 'DRINK', number: 1, options: null },
{ name: 'SLEEP', number: 2, options: null },
{ name: 'CODE', number: 3, options: null },
{ name: 'SKI', number: 4, options: null }
],
name: 'Choices',
options: null
}
Use the enum.
// myNodeApp.js
const myDay = { // plain JSON (or define a gRPC message, same same)
dawn: life.Choices.type.value[1].name,
morning: life.Choices.type.value[0].name,
afternoon: life.Choices.type.value[4].name,
evening: life.Choices.type.value[3].name,
night: life.Choices.type.value[2].name
}
You could write an accessor or utility function to manage the key lookup (by passing the imported grpc enum and index), like so:
export const getEnumByName = function (protoEnum, needle) {
return protoEnum.type.value.find(p => {
return p.name === needle
})
}
export const getEnumByNum = function (protoEnum, needle) {
return protoEnum.type.value.filter(p => {
return p.number = needle
})
}
export const getEnumKeys = function (protoEnum, key = 'name') {
return protoEnum.type.value.map(p => {
return p[key]
})
}
Inverting and assigning a value to a Message is what's already covered in other answers, just set the enum field to the string value using, you guessed it, the string that represents the enum name, which you access using the code above.
This is along the lines of how we do it. Clean and simple, just a touch obscure until you look "under the hood" one day.
Learn more about #grpc/proto-loader and #grpc/grpc-js. Hope this helps someone out there in the wild. :)
If you are using the #grpc/proto-loader library, you can set the option enums to the value String (not the string "String", the constructor function String). Then all enum values will be represented by their name strings.
I know this is a general question but I have exhausted google and tried many approaches.Any feedback is appreciated.
The HTTPClient is Angular 5+ so it returns an object created from the response JSON data. I get a massive JSON response from an endpoint I have no control over and I want to use about 20% of the response in my app and ignore the rest.
I am really trying hard to avoid using a series of templates or export objects or whatever and trying to force this massive untyped Observable into a typed object with hundreds of fields many being Arrays. All I need for the app is just a Array of very small objects with 3 fields per object. The 3 fields are all over within the JSON response and I want to map them to my object .map only seems to work when you are using the full response object and I can't find an example where .map does custom work besides in the case where you are mapping a few fields to 1 object and I am trying to map to an Array of my small objects.
UPDATED
Basically I want this service to return an object of Type DislayData to the module that subscribes to it but I get just an Object back. This is not what I ultimately need to do but if I can prove I can map the body of the response to my needed return type I can then start to break down the response body and return an Array of the Type I really need based on my silly DisplayData object. Thanks again!
export interface DislayData {
body: any;
}
...
export class DataService {
constructor(private http: HttpClient) { }
/** GET data from the black box */
getData(): Observable<DislayData> {
return this.http.get<HttpResponse<any>>(searchUrl, { observe: 'response' })
.pipe(
map(res => {
return res.body as DislayData;
}
tap(res => console.log(//do stuff with entire respoonse also)),
catchError(err => this.handleError(err)));
}
private handleError(error: HttpErrorResponse) {
...
Do you know the structure of the answering object?
If yes, you can do something like this:
item$ = new BehaviorSubject<any>({});
item = {
foo: 'a',
bar: 'b',
iton: [1, 2, 3],
boo: {
far: 'c'
}
};
logNewItem() {
this.item$
.pipe(
map(response => {
if (response.foo
&& response.iton
&& response.iton.length >= 3
&& response.boo
&& response.boo.far) {
let newItem = {
foo: response.foo,
iton2: response.iton[2],
far: response.boo.far
};
console.log(newItem); // output: Object { foo: "a", iton2: 3, far: "c" }
}
})
)
.subscribe();
this.item$.next(this.item);
}
Basically, you can simply make sure the properties exist, call them directly and map them to a better fitting object.
I heavily recommend creating an interface for the object you're receiving and an interface or class for the object you're mapping to. In that case you can also write the code more compact like this:
[...]
map(response: MyAPIResponse => {
let newItem = new NewItem(response);
console.log(newItem); // output: Object { foo: "a", iton2: 3, far: "c" }
}
})
[...]
class NewItem {
foo: string;
iton2: string;
far: string;
constructor(apiResponse: MyAPIResponse) {
//Validate parameter first
this.foo = apiResponse.foo;
this.iton2 = apiResponse.iton[2];
this.far = apiResponse.boo.far;
and make your code a lot more readable.