Type 'undefined' is not assignable to type '{ id: number; name: string; status: string; }' - undefined

Build at: 2021-09-13T04:00:55.316Z - Hash: d597e9c75de38cc870b6 - Time: 2764ms
Error: src/app/servers/edit-server/edit-server.component.ts:18:5 - error TS2322: Type '{ id: number; name: string; status: string; } | undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
Type 'undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
18 this.server = this.serversService.getServer(1);
~~~~~~~~~~~
Error: src/app/servers/server/server.component.ts:16:5 - error TS2322: Type '{ id: number; name: string; status: string; } | undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
Type 'undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
16 this.server = this.serversService.getServer(1);
~~~~~~~~~~~
√ Browser application bundle generation complete.
5 unchanged chunks
Build at: 2021-09-13T04:00:56.000Z - Hash: d597e9c75de38cc870b6 - Time: 393ms
Error: src/app/servers/edit-server/edit-server.component.ts:18:5 - error TS2322: Type '{ id: number; name: string; status: string; } | undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
Type 'undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
18 this.server = this.serversService.getServer(1);
~~~~~~~~~~~
Error: src/app/servers/server/server.component.ts:16:5 - error TS2322: Type '{ id: number; name: string; status: string; } | undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
Type 'undefined' is not assignable to type '{ id: number; name: string; status: string; }'.
16 this.server = this.serversService.getServer(1);

Adding ! to ‘this.serversService.getServer(1)!;’ should fix it because the ‘!’ operator indicates this value isn’t nullable.

Related

How to declare an interface with an array of objects in Angular (typescript)?

I created an Angular project where I'm receiving an object with the following structure from the backend:
{
status: "ok",
totalResults: 12,
articles: [
{
source: {
id: null,
name: "Sports Illustrated"
},
author: "Albert Breer",
title: "Some Title",
description: "Some description",
urlToImage: "http://google.ch/someImage.jpg"
}
]
}
I then tried to create an interface which corresponds to this object. Yet I struggled to define properties that refer to an object resp. an array of objects (e.g. article).
In my first attempt I tried to define my object inline:
export interface Noticias {
status: string;
totalResults: number;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Then I tried to define the properties as duplicates:
export interface Noticias {
status: string;
totalResults: number;
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
articles: Array<{
id: string;
name: string;
title: string;
description: string;
urlToImage: string;
}>
}
Visual Studio Code keeps showing me errors, therefore I doubt whether my approach is correct. Any help would be greatly appreciated!
Based on the json-structure on your first screenshot you'd rather create three separate interfaces: One for Noticias, one for Article and one for Source. Then Noticias contains an array of type Article and Article contains an object of type Source;
noticias.model.ts:
import { Article } from './article.model';
export interface Noticias {
status: string;
totalResults: number;
articles: Article[];
}
article.model.ts:
import { Source } from './source.model';
export interface Article {
source: Source;
author: string;
title: string;
description: string;
urlToImage: string;
}
source.model.ts:
export interface Source {
id: string;
name: string;
}

How to retrieve the value of a json object from Mysql in Graphql

import { GraphQLString, GraphQLScalarType } from 'graphql'
import { city } from '../../Entities/Cities'
export const CREATE_CITY = {
type: Citytype,
args: {
Name: { type: GraphQLString },
CountryCode: { type: GraphQLString },
District: { type: GraphQLString },
Info: { type: GraphQLString }
},
resolve(parent: any, args: any) {
const { Name, CountryCode, District, Info } = args;
city.insert({ Name, CountryCode, District, Info });
return args;
},
}`
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
export class city extends BaseEntity{
#PrimaryGeneratedColumn()
Id!: number;
#Column({ type: "char", length: 35 })
Name!: string;
#Column({ type: "char", length: 3 })
CountryCode!: string;
#Column({ type: "char", length: 20 })
District!: string;
#Column({ type: "string" })
Info!: string;
}
<I'm trying to learn graphql and I'm a day in>
The Info type is suppose to be a json, in my database it looks like {"Population": 127800} with the same definition. I'm fully aware that it isn't a string/GraphQLString but I don't know how to obtain the value of this object. It returns Info: null and an error - "message": "String cannot represent value: { Population: 127800 }" for obvious reasons.
The code has the same structure as the tutorial I watched and only this video.
Link: https://www.youtube.com/watch?v=fov5e6XJgwc&ab_channel=PedroTech
Q: I want to know how to get the population ex. {"Population": 127800} when I query
it should look like Info: {"Population": 127800}
Optional: How to get the value of population if it looks like - Info: 127800

sequelize with typescript can not use .create with type attributes

The IDBAttribute -
interface IDBAtribute {
readonly id: number;
readonly createdAt: Date;
readonly updatedAt: Date;
}
The User attributes -
interface IDBMoviesAttributes extends IDBAttribute {
readonly title: string;
readonly description: string;
readonly category: string;
readonly release_date: number;
readonly movie_hour_length: number;
readonly movie_minute_length: number;
readonly image_path: string;
readonly video_path: string;
}
The User model -
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
import { IDBUserAttributes } from "./shared/db-table";
interface UserModel extends Model<IDBUserAttributes>, IDBUserAttributes {}
class User extends Model<UserModel, IDBUserAttributes> {}
type UserStatic = typeof Model & {
new (values?: object, options?: BuildOptions): UserModel;
};
const UserFactory = (sequelize: Sequelize): UserStatic => {
return <UserStatic>sequelize.define("users", {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
unique: true,
allowNull: false,
},
email: {
type: DataTypes.STRING(320),
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING(26),
allowNull: false,
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW,
},
});
}
export {
UserModel,
User,
UserFactory,
UserStatic,
}
I'm Using the User for .create method in sequelize like this -
User.create({
email: req.body.email,
username: req.body.username,
password: hashedPassword,
})
The error -
Argument of type '{ email: string; username: string; password: string; }' is not assignable to parameter of type 'IDBUserAttributes'.
Type '{ email: string; username: string; password: string; }' is missing the following properties from type 'IDBUserAttributes': id, createdAt, updatedAtts(2345)
I know to error is type error but i don't know any other why to the User model, is there any other way I can achive that? I don't need to create the id,createdAt, updatedAt.
How can I get the model in the correct way?
Try making id ,createdAt ,updatedAt as Optional(?) in IDBUserAttributes.
It might work
Example:
interface IDBUserAttributes {
id?: number;
createdAt?: Date;
updatedAt?: Date;
}
const newObjectData: Request['body'] = {
user_id: 1
};
and now, you can use "create" method like this;
await Model.create(newObjectData);

Angular4 error message shows code which differs from the code that's supposed to be serving

I'm writing an app to go into a website, which is intended to calculate simplex algorithms. At the moment I am attempting to create functionality whereby the user can enter the number of coefficients and constraints, name these whatever they wish, and have the app spawn the relevant number and type of UI elements relative to the user's input. Here's what appears to be the relevant portion of the code (app.component.ts):
import { Component } from '#angular/core';
[...]
export class UIComponent {
id: 1;
name: string;
value: number;
type: string;
}
//* Mock data */
const UICOMPONENTS: UIComponent[] = [
{ id: 1, name: 'coefficient1', value: 4, type: '1dslide' },
{ id: 2, name: 'constraint1', value: 2, type: '2dslide' },
{ id: 3, name: 'min_max', value: 0, type: 'switch' },
{ id: 4, name: 'profit', value: 100, type: 'num_output' }
];
[...]
export class AppComponent {
title = 'SimutronX';
uicomponents = UICOMPONENTS;
[...]
}
This produces an error on screen saying:
Failed to compile.
/root/simutronx/simutron-app/src/app/app.component.ts (18,49): ',' expected.
Which relates to this line:
{ id: 2, name: 'constraint1', value: 2, type: '2dslide' },
Specifically the digit 2 in 2dslide. The error message (it's extremely long so I won't reproduce it all) also includes:
./src/app/app.component.ts
Module parse failed: /root/simutronx/simutron-app/node_modules/#ngtools/webpack/src/index.js!/root/simutronx/simutron-app/src/app/app.component.ts Unexpected token (22:85)
You may need an appropriate loader to handle this file type.
| var UICOMPONENTS = [
| { id: 1, name: 'coefficient1', value: 4, type: '1dslide' },
| { id: 2, name: 'constraint1, value: 2, type: ', 2: dslide, ' },: { id: 3, name: 'min_max', value: 0, type: 'switch' }, },
| { id: 4, name: 'profit', value: 100, type: 'num_output' }
| ];
Which is particularly confusing since, as you can see, that's not how I wrote the code. What's going on here?
You have an error in UIComponent type :
export class UIComponent {
id: number; //HERE
name: string;
value: number;
type: string;
}
Here a plunker :http://plnkr.co/edit/e6GrylSWznwbYD9VpK2C

json array 1st one get value of 2nd one

In Angular2, I have a JSON that returns Customer
Here is my Customer class:
export class Customer {
customerNo: string;
tckn: string;
vkn: string;
customerType: string;
address: Address[];
phone: Phone[];
}
and here is my Address class:
export class Address {
addressType: string;
tradeName: string;
taxOfficeName: string;
taxNo: string;
addressName: string;
addressString: string;
building: string;
floor: string;
apartment: string;
city: string;
county: string;
zipCode: string;
addressDirection: string;
department: string;
indx:string;
}
And here is my json in my customer.service.ts;
getCustomerInfo(): any {
return [{
customerNo: '4767584',
tckn: '968796',
customerType: '1',
address: [{
addressName: '1.address',
addressType: '1',
city: '34',
taxNo: '111'
},
{
addressName: '2.address',
addressType: '2',
city: '6',
apartment: 'test aprt'
}
]
}];
}
I append that json to my model in customer.component.ts
this.model = this._customerService.getCustomerInfo()[0] as Customer;
now I log this._customerService.getCustomerInfo()[0] as Customer;
and I see that json is ok.
now, log this.model the 1st address get values of 2nd address
do you have any idea why this is happening?