Instantiating MediaDeviceInfo results in 'Illegal constructor' - javascript

Is it possible to instantiate my own instance of MediaDeviceInfo? Both of these fail:
new MediaDeviceInfo();
new MediaDeviceInfo({
deviceId: 'Brad Test',
groupId: 'Brad Test',
kind: 'audioinput',
label: 'Brad Test'
});
Uncaught TypeError: Illegal constructor

No, there is no constructor defined on the interface: https://w3c.github.io/mediacapture-main/#device-info

Related

How to define a typescript type for a dictionary with generic keys?

While trying to map the keys of data I'm getting several Typescript errors and I don't understand why. I'm getting back as a response from my API an object with generic keys as followed:
{
1: {
name: 'test1',
country: 'test1',
},
2: {
name: 'test2',
country: 'test2',
}
....generic amount of keys
}
I have defined the following typescript type for this:
export type Users<T> = {
[K in keyof T]: {
name: string;
country: string;
};
};
When I'm trying to map on the keys of this typed object in my component I'm gtting an error from typescript:
Object.keys(data).map((key) => {
<p>{data[key].name}</p>
})
Error on Object.keys(data) line:
const data: Users | undefined No overload matches this call.
Overload 1 of 2, '(o: {}): string[]', gave the following error.
Argument of type 'Users | undefined' is not assignable to parameter of type '{}'.
Type 'undefined' is not assignable to type '{}'. Overload 2 of 2, '(o: object): string[]', gave the following error.
Argument of type 'Users | undefined' is not assignable to parameter of type 'object'.
Type 'undefined' is not assignable to type 'object'.ts(2769) No quick fixes available
Error on data[key].name:
Object is possibly 'undefined'.
From the TSConfig reference noUncheckedIndexedAccess:
TypeScript has a way to describe objects which have unknown keys but known values on an object, via index signatures.
Turning on noUncheckedIndexedAccess will add undefined to any un-declared field in the type.
You can use the non-null assertion operator (postfix !) to inform the compiler that the value definitely exists. Here's an example:
TS Playground
import {default as React} from 'react';
type User = {
name: string;
country: string;
}
const data: Record<string, User> = {
1: {
name: 'test1',
country: 'test1',
},
2: {
name: 'test2',
country: 'test2',
},
// ....generic amount of keys
};
Object.keys(data).map(key => (<p>{data[key]!.name}</p>));
// ^
// The non-null assertion operator will assert
// to the compiler that the value exists

Getting 'Cannot read property of undefined' when accessing an array object

I have this object defined based on the elements that I retrieved from my HTTP request. The problem is that I'm trying to access these elements in the Object Array, I'm getting this 'Cannot read property of undefined' error. Can you please advise where do I go wrong? Because I think I'm accessing it the right way.
console image
app.module.ts
export class AppComponent {
...
public blockchain;
constructor(private blockchainService: BlockchainService) {
this.blockchain = blockchainService.blockchainInstance;
}
ngOnInit() {
}
...
}
Object class
export class BlockchainDB {
id?: any;
provider?: string;
recipient?: string;
rxInfo?: string;
timestamp?: string;
published?: boolean;
}
Code
export class BlockchainService {
...
currentBlockchain: BlockchainDB = {
rxInfo: '',
provider: '',
recipient: '',
timestamp: '',
published: false
};
...
public sampledata = [];
public arraydata3: BlockchainDB [];
constructor(private blockchainService: BlockchainDBService) {
this.retrieveBlockchain();
this.createChainData();
console.log(this.arraydata3);
console.log(this.arraydata3[0].rxInfo);
}
createChainData() {
this.getBlockchain('1', 0);
this.getBlockchain('2', 1);
}
getBlockchain(id: string, seqnr: number): void {
console.log(id);
this.blockchainService.get(id)
.subscribe(
data => {
this.currentBlockchain = data;
this.arraydata3.push(this.currentBlockchain);
console.log(data);
},
error => {
console.log(error);
});
}
Debug Logs
1
blockchain.service.ts:78 2
blockchain.service.ts:50 Array(2)0: {id: 1, provider: "steve", recipient: "me", rxInfo: "{brandname:neozep,genericname:paracetamol,prescribedDosageCount:20}", timestamp: "1630747314781", …}1: {id: 2, provider: "qwerty", recipient: "trewq", rxInfo: "{brandname:biogesic,genericname:paracetamol,prescribedDosageCount:20}", timestamp: "1730747314781", …}length: 2[[Prototype]]: Array(0)
core.js:6479 ERROR TypeError: Cannot read property 'rxInfo' of undefined
at new BlockchainService (blockchain.service.ts:51)
at Object.BlockchainService_Factory [as factory] (blockchain.service.ts:122)
at R3Injector.hydrate (core.js:11438)
at R3Injector.get (core.js:11257)
at NgModuleRef$1.get (core.js:25332)`enter code here`
at Object.get (core.js:25046)
at lookupTokenUsingModuleInjector (core.js:3342)
at getOrCreateInjectable (core.js:3454)
at Module.ɵɵdirectiveInject (core.js:14737)
at NodeInjectorFactory.AppComponent_Factory [as factory] (app.component.ts:9)
defaultErrorLogger # core.js:6479
main.ts:12 TypeError: Cannot read property 'rxInfo' of undefined
at new BlockchainService (blockchain.service.ts:51)
at Object.BlockchainService_Factory [as factory] (blockchain.service.ts:122)
at R3Injector.hydrate (core.js:11438)
at R3Injector.get (core.js:11257)
at NgModuleRef$1.get (core.js:25332)
at Object.get (core.js:25046)
at lookupTokenUsingModuleInjector (core.js:3342)
at getOrCreateInjectable (core.js:3454)
at Module.ɵɵdirectiveInject (core.js:14737)
at NodeInjectorFactory.AppComponent_Factory [as factory] (app.component.ts:9)
The code inside the subscription is executed when the api call is completed which is asynchronous.
Therefore, "console.log(this.arraydata3[0].rxInfo);" is executed before "this.arraydata3.push(this.currentBlockchain);"
You can handle this asynchronous behvior by following this solution

res in controller function fails due to being undefined

I'm new to Sails (and a jr. dev to boot) and have been working through the Sailsjs in Action book. Given some previous experience with TypeScript I wanted to experiment with the framework in that capacity. However I've hit a road block when trying to return response statuses and information via my API.
Every time I try to use the res in my controller I receive a:
TypeError: Cannot read property 'ok' of undefined. Based on the book and the documentation, I'm under the impression that would get set automatically per this example from the docs:
await User.create({name:'Finn'});
return res.ok();
and this example from the book:
signup: function(req, res) {
var options = {**grab request data**};
User.create(options).exec(function(err, createdUser){
if(err){
return res.negotiate(err);
}
return res.json(createdUser);
}
So I feel like I'm missing something pretty obvious but I'm not sure what. The project compiles just fine and I've got the documented typescript libraries installed/configured. Even matching that function there returns the same TypeError to me.
Another set of eyes would be greatly appreciated. Controller code below.
declare const sails: any;
import { boatInterface } from '../../interfaces/boat';
module.exports = {
friendlyName: 'new-boat',
description: 'create a new boat model',
inputs: {
modelName:{
required: true,
type: 'string',
},
yearBuilt:{
required: true,
type: 'number'
}
},
exits: {
success: {
description: 'New boat model was created successfully.'
},
invalid: {
responseType: 'badRequest',
description: 'The provided boat info was invalid.'
},
modelAlreadyCreated: {
statusCode: 409,
description: 'The provided boat model has already been
created.',
},
},
fn: async function (req: any, res: any){
console.log('building boat');
let boatRequest: boatInterface = {
modelName: req.modelName.toLowerCase(),
yearBuilt: req.yearBuilt
}
//confirming data has been formatted correctly
console.log(boatRequest);
let newBoat = await sails.models.boat.create(boatRequest)
.intercept('E_UNIQUE', 'modelAlreadyCreated')
.fetch();
//confirming new boat exists
console.log(newBoat);
console.log("request successful");
//res remains undefined and throws an error on attempted return
console.log(res);
return res.ok();
}
};
Here's the error with some console logs included. Thanks in advance!
building boat
{ modelName: 'kraken', yearBuilt: 1337 } <-- Request formats correctly
{ createdAt: 1566173040652,
updatedAt: 1566173040652,
id: 6,
modelName: 'kraken',
yearBuilt: 1337 } <-- new db entry is returned via fetch()
request successful
undefined <-- attempt to log the res returns undefined
(node:3738) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ok' of undefined
at Object.<anonymous> (/Users/pitterpatter/Repos/learn/sails-learn/freeform/api/controllers/boat/new-boat.ts:67:20)
It looks like you're using actions2.
Your handler function will be given 2 parameters - inputs and exits as you've defined in the objects above it.
fn: async function (inputs: any, exits: any) {
inputs will be an object that contains parmeters given by a user that you've defined in the inputs part of your action (form data/query parameters/route parameters).
In this case it'd contain a modelName and yearBuilt, something like
{ modelName: 'lemon', yearBuilt: 2012.3 }
exits will contain a few default methods - exits.success() and exits.error(), as well as the invalid and modelAlreadyCreated which you've defined.
TLDR try this
fn: async function (inputs: any, exits: any) {
let boatRequest: boatInterface = {
modelName: inputs.modelName.toLowerCase(),
yearBuilt: inputs.yearBuilt
}
let newBoat = await sails.models.boat.create(boatRequest)
.intercept('E_UNIQUE', 'modelAlreadyCreated')
.fetch();
return exits.success(newBoat);
}
You can access the "raw express response object" deely that you're looking for by using this.res.ok(...) or this.req.something, but it's recommended you use the appropriate "exit" instead.

TypeError: Object doesn't support property or method 'entries' (IE11)

I have an app written in Aurelia which needs to run in IE11.
Until last week the app was running ok but now I get the following error in the console when I try running it
TypeError: Object doesn't support property or method 'entries'
I have no idea what's caused this. I've gone back commits to a month ago, where the app was definitely working in IE11, but I get the same error.
We are using Yarn for package management with Webpack
The full stack dump is:
{
[functions]: ,
__proto__: { },
__symbol:__symbol:rxSubscriber0.6484791277649529: undefined,
__symbol:hasInstance0.64847912776495296: undefined,
__symbol:isConcatSpreadable0.64847912776495297: undefined,
__symbol:iterator0.64847912776495291: undefined,
__symbol:match0.64847912776495292: undefined,
__symbol:replace0.64847912776495293: undefined,
__symbol:search0.64847912776495294: undefined,
__symbol:species0.64847912776495299: undefined,
__symbol:split0.64847912776495295: undefined,
__symbol:toPrimitive0.648479127764952910: undefined,
__symbol:toStringTag0.648479127764952911: undefined,
__symbol:unscopables0.64847912776495298: undefined,
description: "Object doesn't support property or method 'entries'",
message: "Object doesn't support property or method 'entries'",
name: "TypeError",
number: -2146827850,
stack: "TypeError: Object doesn't support property or method 'entries'
at createSelectors (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:28145:9)
at target.prototype[] (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:28176:13)
at bind (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:36702:7)
at bind (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:38733:7)
at automate (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:38678:5)
at ready (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:48132:7)
at swap (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:48161:5)
at Anonymous function (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-24hxcAM:48682:9)
at Anonymous function (http://localhost:51158/dist/app.js?v=Q8Lj1h7qjQUyqYO52tjHs-75tv3cmxHiL7p-2"
}
I've tried looking at other SOF posts but I haven't been able to find a clear answer on what I should do - can anyone help?
Edit:
I just installed this polyfill and ran Webpack and now I'm getting this error:
ERROR [app-router] SyntaxError: Syntax error
"ERROR [app-router]"
{
[functions]: ,
__proto__: { },
__symbol:__symbol:rxSubscriber0.7605681080912143: undefined,
__symbol:hasInstance0.76056810809121436: undefined,
__symbol:isConcatSpreadable0.76056810809121437: undefined,
__symbol:iterator0.76056810809121431: undefined,
__symbol:match0.76056810809121432: undefined,
__symbol:replace0.76056810809121433: undefined,
__symbol:search0.76056810809121434: undefined,
__symbol:species0.76056810809121439: undefined,
__symbol:split0.76056810809121435: undefined,
__symbol:toPrimitive0.760568108091214310: undefined,
__symbol:toStringTag0.760568108091214311: undefined,
__symbol:unscopables0.76056810809121438: undefined,
description: "Syntax error",
message: "Syntax error",
name: "SyntaxError",
number: -2146827286,
stack: "SyntaxError: Syntax error
at tryCatcher (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:6757:9)
at Promise.prototype._settlePromiseFromHandler (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:4779:9)
at Promise.prototype._settlePromise (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:4836:13)
at Promise.prototype._settlePromise0 (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:4881:5)
at Promise.prototype._settlePromises (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:4960:13)
at Async.prototype._drainQueue (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:1689:13)
at Async.prototype._drainQueues (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:1699:5)
at drainQueues (http://localhost:51158/dist/app.js?v=yJ9KRojv8-WpvAUoTKrlQU3TjmNSInH-YMQzLwKD_0g:1573:9)
"
}
As people have mentioned, the fix for this was to implement the following polyfill
if (!Object.entries)
Object.entries = function (obj) {
var ownProps = Object.keys(obj),
i = ownProps.length,
resArray = new Array(i); // preallocate the Array
while (i--)
resArray[i] = [ownProps[i], obj[ownProps[i]]];
return resArray;
};

Realm React Native - Migration is required: Target type 'string' doesn't exist for property 'emailAddresses'

I am building a small app with React Native and want to use Realm for persistency.
I defined the following schema for a Person:
const personSchema = {
name: 'Person',
properties: {
familyName: {type: 'string', optional: true},
givenName: {type: 'string'},
middleName: {type: 'string', optional: true},
emailAddresses: {type: 'list', objectType: 'string'},
}
}
export class Person {}
Person.schema = personSchema
The information as to how a Realm schema needs to be defined can be found in the Realm docs.
I then instantiate the DB like so:
const schemas = [Person]
const db = new Realm({schema: schemas})
However, there is an exception when reaching the last line giving me the following error:
Unhandled JS Exception: Migration is required due to the following
errors:
Target type string doesn't exist for property emailAddresses.
I am using the iOS simulator for testing and deleted the app several times and then reinstalled it using the play button in Xcode.
Does anyone have an idea why I am getting this exception?
Update
I now created a separate schema for another db object: EmailAdress
const emailAddressSchema = {
name: 'EmailAddress',
properties: {
label: 'string',
email: 'string'
}
}
export class EmailAddress {}
EmailAddress.schema = emailAddressSchema
I also changed the objectType of emailAddresses in the personSchema to be of type EmailAddress now:
...
emailAddresses: {type: 'list', objectType: 'EmailAddress'},
...
Now, I am not getting the exception any more. Isn't it possible to add a property to a Realm class that is a list of strings?
Lists of primitives are not yet supported in Realm. Until they are you need to wrap primitive types in an object as you have done with EmailAddress

Categories

Resources