Vue 3 TypeScript - Property 'searchData' does not exist on type 'CreateComponentPublicInstance - javascript

im trying to use function as a computed value in defineComponent:
code printscreen
<script lang="ts">
import { defineComponent } from "#vue/runtime-core";
import { testData } from "../assets/testData";
export type SearchDataType = {
_id: string;
index: number;
name: string;
};
interface ISearchPage {
searchData: SearchDataType[];
searchQuery: string
}
export default defineComponent({
name: "SearchPage",
components: {},
data(): ISearchPage {
return {
searchData: [],
searchQuery: ''
};
},
methods: {
getData: function () {
this.searchData = testData;
},
},
created(){
this.getData()
},
computed: {
filteredSearch: function() {
return this.searchData.filter((filteredItem: SearchDataType) => {
return filteredItem.name.match(this.searchQuery)
})
}
}
});
</script>
And, when i want to use this.searchData variable in computed im reciving the following errors:
Property 'searchData' does not exist on type 'CreateComponentPublicInstance<{ [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, ... 10 more ..., {}>'.
Property 'searchData' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: { [x: string & `on${string}`]: ((...args: any[]) => any) | undefined; } | { [x: string & `on${string}`]: undefined; }; ... 10 more ...; $watch(source: string | Function, cb: Function, options?: WatchOptions<...> | undefined): WatchStopHandle; } & ... 4 more ... & Co...'
I was trying to add the code below to shims-vue.d.ts file, but it didn't solve the problem:
import { ComponentCustomProperties } from "vue";
declare module "#vue/runtime-core" {
interface CreateComponentPublicInstance {
searchData: any | null;
}
}
Im new to vue with TypeScript. Could someone tell me, what am doing wrong?

Related

HMS Core location Kit TypeError: Cannot read properties of undefined (reading 'getFusedLocationProviderClient') - Ionic/Capacitor - VueJS

I'm trying to implement HMS Core location kit into my vue ionic app.
I import HMSLocation and declare it, but when I try to use the getFusedLocationProviderClient function I get
TypeError: Cannot read properties of undefined (reading 'getFusedLocationProviderClient')
import { HMSLocation } from "#hmscore/ionic-native-hms-location/ngx";
export default {
data() {
return {
hmsLocation: null,
fusedClient: null,
locationResult: null,
};
},
mounted() {
this.getLocation();
},
methods: {
async getLocation() {
this.hmsLocation = new HMSLocation();
console.log(this.hmsLocation);
this.fusedClient = this.hmsLocation.getFusedLocationProviderClient();
this.locationResult = await this.fusedClient.getLastLocation;
},
},
.....
console.log(this.hmsLocation); returns
node_modules/#hmscore/ionic-native-hms-location/ngx
import { IonicNativePlugin } from '#ionic-native/core';
export declare class HMSLocation extends IonicNativePlugin {
getGeofenceService(): GeofenceService;
getGeocoderService(language: string, country?: string): GeocoderService;
getFusedLocationProviderClient(): FusedLocationService;
getActivityIdentificationService(): ActivityIdentificationService;
addListener(event: Events, callback: (data: LocationResult | [] | ActivityConversionResponse | ActivityIdentificationResponse) => void): any;
disableLogger(): Promise<void>;
enableLogger(): Promise<void>;
}
export declare class BackgroundManager {
private constructor();
static notify(notificationId: number, notification: string): void;
static makeToast(text: string, duration: number): void;
}
export interface FusedLocationService {
disableBackgroundLocation(): Promise<void>;
enableBackgroundLocation(notificationId: number, notification: string): Promise<void>;
checkLocationSettings(request: LocationSettingsRequest): Promise<LocationSettingsStates>;
flushLocations(): Promise<void>;
getLastLocation(): Promise<Location>;
getLastLocationWithAddress(request: LocationRequest): Promise<HWLocation>;
getLocationAvailability(): Promise<boolean>;
getNavigationContextState(requestType: NavigationRequestConstants): Promise<NavigationResult>;
removeLocationUpdates(requestCode: number, type: RequestType): Promise<boolean>;
requestLocationUpdates(requestCode: number, request: LocationRequest, callback?: (locationResult: LocationResult) => void): Promise<boolean>;
requestLocationUpdatesEx(requestCode: number, request: LocationRequest): Promise<boolean>;
setMockLocation(latLng: LatLng): Promise<void>;
setMockMode(mode: boolean): Promise<void>;
setLogConfig(logConfigSettings: LogConfigSettings): Promise<void>;
getLogConfig(): Promise<LogConfigSettings>;
}

React overload on Typescript - CombineReducer

I am currently using a redux pattern in a create-react-app with typescript.
Currently i am having an issue deciphering the overload error messages.
The current fix works but i dont think its correct as it wont be strictly typed anymore.
const combinedReducers = combineReducers({ reducer1, reducer2 } as any);
Overload Error message:
No overload matches this call.
Overload 1 of 3, '(reducers: ReducersMapObject<ApplicationState, any>): Reducer<CombinedState<ApplicationState>, AnyAction>', gave the following error.
Type '(state: ModelState | undefined, action: any) => { model: any; loading: boolean; errorMessage: string; } | { loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'Reducer<ModelState, any>'.
Type '{ model: any; loading: boolean; errorMessage: string; } | { loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'ModelState'.
Type '{ loading: boolean; errorMessage: any; model: never[]; }' is not assignable to type 'ModelState'.
Types of property 'model' are incompatible.
Type 'never[]' is missing the following properties from type 'Model': opportunity_id, model_result TS2769
24 | save_opportunity_state: SaveOpportunityReducer,
25 | archive_state: ArchiveOpportunityReducer,
> 26 | model_state: GetModelReducer,
| ^
27 | });
28 |
Reducer:
export interface ModelState {
model: Model;
loading: boolean;
errorMessage: string;
}
export interface Model {
opportunity_id: string;
model_result: ModelResult;
}
export interface ModelResult {
model_info: ModelInfo;
qualification: Qualification;
similar_deals?: null[] | null;
tool_tips: ToolTips;
top_actions?: null[] | null;
win_probability: WinProbability;
}
export interface ModelInfo {
probability_version: string;
similar_deals_version: string;
}
export interface Qualification {
colour: string;
score: number;
}
export interface ToolTips {
[key: string]: string;
}
export interface WinProbability {
colour: string;
features?: null[] | null;
score: number;
}
const initialState: ModelState = {
model: {
opportunity_id: '',
model_result: {
model_info: { probability_version: '', similar_deals_version: '' },
qualification: { colour: 'grey', score: 0 },
similar_deals: [],
tool_tips: {},
top_actions: [],
win_probability: { colour: 'green', features: [], score: 0 },
},
},
loading: false,
errorMessage: '',
};
If you look at the error message, specifically the last one states that model is missing following property.
I am guessing your failure case just returns an empty object. This contradicts the types defined above as the model should always contain x, y and z.
So in your failure case, you should add the following:
model: { ...initialState.model },

Extending Interface/types in typescript

I have extended my FilterMetaData type to add a dynamic model which is different structure for different entities but somehow typescript not recognizing my object properties. I might be missing something here.
Interfaces
export type FilterMetaData<T extends {}> = T & {
filterCriteriaID: number;
filterCriteriaName?: string;
isDefaultSelected?: boolean;
isExpanded?: boolean;
}
export interface DateRange {
data?: DateRangeData;
}
export interface DateRangeData {
min?: Date;
max?: Date;
}
export interface Range {
data?: RangeData;
}
export interface RangeData {
currency?: string;
timePeriod?: string;
min?: number;
max?: number;
step?: number;
}
export interface Select {
data?: SelectData[];
}
export interface SelectData {
id?: number;
name?: string;
isSelected?:boolean|false;
parentID?: number | null;
parentName?: string;
}
Implementation in class
helper<T1 extends FilterMetaData<T2>>(filter) {
this.selectedFilterService.getAppliedFilterMasterData<T1>(filter)
.pipe(takeUntil(this.unsubscribe$))
.subscribe((filterData: T1) => {
if (filter.isDefaultSelected) {
filterData.isExpanded = false;
filterData.data.forEach((data) => data.isSelected = false);
this.selectedFilters.result.select.push(filterData);
this.loadComponent(new FilterComponentType(SelectComponent, filterData));
} else {
this.removeComponent(filter);
}
}, err => {
this.toastrService.error(err);
})
}
Invoking Function with type args like this:--
this.helper<FilterMetaData<Select>>(filter);

MediaStreamRecorder is not a constructor

I'm new to Angular6 and I'm trying to use MediaStreamRecorder. I'm definitely doing something wrong when defining MediaStreamRecorder because I keep getting the error TypeError: msr__WEBPACK_IMPORTED_MODULE_4__.MediaStreamRecorder is not a constructor. Not sure how or where should I declare and define MediaStreamRecorder. Can you help me with this, please?
I have installed msr module, and my code looks like this:
import { Component,ViewChild, OnInit, Inject } from '#angular/core';
import { LinksService } from 'demo/_services/links.service';
import { Http,Response,Headers } from '#angular/http';
import { MediaStreamRecorder} from 'msr';
import { RecordRTC } from 'recordrtc';
#Component({
selector: 'demo-ceva',
templateUrl: './ceva.component.html',
styleUrls: ['./ceva.component.css'],
providers: [
{
provide: SpeechRecognitionLang,
useValue: 'en-US',
},
SpeechRecognitionService,
],
})
export class CevaComponent {
public navigator: any;
public MediaStreamRecorder: any;
constructor( private http: Http, private service: SpeechRecognitionService, private links: LinksService ) {
this.record = () => {
var browser = <any>navigator;
var obj = { audio: true, video:false };
browser.getUserMedia = (browser.getUserMedia || browser.webkitGetUserMedia || browser.mozGetUserMedia || browser.msGetUserMedia);
browser.mediaDevices.getUserMedia(obj).then(stream => {
var source = window.URL.createObjectURL(stream);
var config= { ... }
var recorder = new MediaStreamRecorder(stream, config);
recorder.record();
recorder.stop(function(blob) {
var blob = recorder.blob;
console.log(blob);
});
});
});
As the answer to this post suggested, the solution to me was that in typings.d.ts file to add the following declarations:
declare interface MediaRecorderErrorEvent extends Event {
name: string;
}
declare interface MediaRecorderDataAvailableEvent extends Event {
data : any;
}
interface MediaRecorderEventMap {
'dataavailable': MediaRecorderDataAvailableEvent;
'error': MediaRecorderErrorEvent ;
'pause': Event;
'resume': Event;
'start': Event;
'stop': Event;
'warning': MediaRecorderErrorEvent ;
}
declare class MediaRecorder extends EventTarget {
readonly mimeType: string;
// readonly MimeType: 'audio/wav';
readonly state: 'inactive' | 'recording' | 'paused';
readonly stream: MediaStream;
ignoreMutedMedia: boolean;
videoBitsPerSecond: number;
audioBitsPerSecond: number;
ondataavailable: (event : MediaRecorderDataAvailableEvent) => void;
onerror: (event: MediaRecorderErrorEvent) => void;
onpause: () => void;
onresume: () => void;
onstart: () => void;
onstop: () => void;
constructor(stream: MediaStream);
start();
stop();
resume();
pause();
isTypeSupported(type: string): boolean;
requestData();
addEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
And in my component, I was able to use var mediaRecorder = new MediaRecorder(stream); without any other declarations. Thank you, #firegloves , for the link to this post and thank you, #Tiberiu C. for the answer! It was really helpful.
npm install -D #types/dom-mediacapture-record
I had the same issue with pure JS and React and removing the following line "fixed" the problem:
window.MediaRecorder = require('audio-recorder-polyfill');

Cannot find namespace error for model in Angular2/TypeScript

The FeaturedCategories model
export class FeaturedCategories {
categories: Array<{ id: number, title: string, graphic: string, categorycards: Array<{}> }>;
}
Also tried this:
export class FeaturedCategories {
id: number;
title: string;
graphic: string;
categorycards: Object[];
}
The Component
import { Component, ChangeDetectionStrategy, ViewEncapsulation } from '#angular/core';
import { ApiService } from '../shared/services/api.service';
import { FeaturedCategories } from '../shared/models/home/featuredcategories';
#Component({
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated,
selector: 'home',
styleUrls: [ './home.component.css' ],
templateUrl: './home.component.html'
})
export class HomeComponent {
testFeaturedCategories: Array<FeaturedCategories>;
constructor(private api: ApiService) {
// we need the data synchronously for the client to set the server response
// we create another method so we have more control for testing
this.universalInit();
}
universalInit() {
console.log('universalInit...')
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
this.testFeaturedCategories = categories
});
}
}
This will work: testFeaturedCategories: Array<{}>;
However I'm trying to use TypeScript to let my App know what type of model to expect.
This causes the error above:
testFeaturedCategories: FeaturedCategories.categories;
And if I just try this: testFeaturedCategories: FeaturedCategories;
I get a type [{}] is not assignable error.
UPDATE
So I noticed that when I commented out all the keys in my FeaturedCategories model finally the error goes away and
featuredCategories: FeaturedCategories[]; will work.
However now this is just an empty object without keys to expect :(
export class FeaturedCategories {
// id: number;
// title: string;
// graphic: string;
// categorycards: Object[];
}
this is working fine for me.
export class MyComponent {
categories: FeaturedCategories[] = [{
id: 1,
title: "",
graphic: "",
categorycards: [{}]
}];
}
export class FeaturedCategories{
id: number;
title: string;
graphic: string;
categorycards: Object[];
}
My problem was trying to type my Array, instead of just using the Typed objects that exist in the larger Array.
Also had a problem in my service, originally I had this:
/**
* Get featured categories data for homepage
* /wiki
*/
getFeatured(): Observable<[{}]> {
return this.http.get(`${this.getFeaturedUrl}/home`)
// .do(res => console.log('getFeatured res', res.json()))
.map(res => res.json())
.catch(this.handleError);
}
I did not need or could even use a type for my larger Categories array, what I needed was a smaller type for the exact Objects that exist in that larger Array:
export class FeaturedCategory {
id?: number;
type: string;
title: string;
graphic?: string;
video?: string;
categorycards: Array<{}>;
}
So now with the correct Type of Objects inside my Array I added it to the service:
getFeatured(): Observable<[FeaturedCategory]> {
return this.http.get(`${this.getFeaturedUrl}/home`)
.map(res => res.json())
.catch(this.handleError);
}
Now back in my Component I imported the single Typed Object
import { FeaturedCategory } from '../shared/models/home/featuredcategory';
Then typed the variable:
featuredCategories: Array<FeaturedCategory>;
And finally in ngOnInit
ngOnInit() {
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
this.featuredCategories = categories;
});
}
No more errors :)

Categories

Resources