null
ты должен сделать так, чтобы там не было null
. Довольно очевидно, да.const data = useSelector(state => state.DataState.Data) ?? defaultData;
Либо так:if (favorite && data) {
const RunOutsideAngular = (target: any, memberName: string) => {
const method = target[memberName];
return Object.defineProperty(target, memberName, {
writable: true,
configurable: true,
value(...args: any[]) {
return this.ngZone.runOutsideAngular(method.bind(this, ...args))
}
});
};
const RunOutsideAngularAll = (constructor: Function) => {
const keys = new Set<string>();
let proto = constructor.prototype;
do {
if(proto === Object.prototype) break;
Object.getOwnPropertyNames(proto).forEach(
key => typeof proto[key] === 'function'
&& key !== 'constructor'
&& keys.add(key)
);
} while (
proto = Object.getPrototypeOf(proto)
);
keys.forEach(key => RunOutsideAngular(constructor.prototype, key));
}
class SomeClass {
@RunOutsideAngular
myFunc() {
mycode.....
}
}
// или
@RunOutsideAngularAll
class SomeClass {
myFunc() {
mycode.....
}
}
RunOutsideAngular
- по-хорошему надо типизировать дженериком под ангуляр.RunOutsideAngularAll
- обрабатывает все методы и функции, в т.ч. унаследованные, можно упростить чтоб работал только с методами текущего класса. type
будет строго одно из "direct" | "fanout" | "headers" | "topic"
, а получает просто string
.return (await this.rascal.create(RascalConfig as BrokerConfig))
Но это чревато ошибками в самом конфиге.const RascalConfig: BrokerConfig = { ... }
const RascalConfig = { ... } as const
let routes = await axios(...)
.then((response: AxiosResponse<Route[]>) => response.data)
.catch(console.log);
Нет смысла гонять из пустого в порожнее.package.json
и всё что с ним связано - это экосистема node. Из-за удобства и универсальности она принята за стандарт для всей разработки фронта, но браузер об этом ничего не знает. npm i -D @types/google.maps
methods: {
openUnit(it: string):void {
void this.$router.push(`/unit/${it}`);
}
}
methods: {
openUnit(it: string) {
return this.$router.push(`/unit/${it}`);
}
}
methods: {
async openUnit(it: string) {
await this.$router.push(`/unit/${it}`);
}
}
let key: keyof EventStatusType;
for (key in eventTypes) {
Typescript не может автоматически вывести тип key
потому что он структурный, и никак не может знать, что в объекте точно нет ещё каких-нибудь ключей, кроме тех что указаны в типе EventStatusType
: const foo = {
Closed: false,
Maintaince: false,
Open: false,
внезапно: 'Вася'
};
const bar: EventStatusType = foo; // ok
Поскольку с помощью кода в начале ты фактически говоришь Typescript: "я знаю лучше, там точно не будет ничего другого", то на всякий непредвиденный случай следует добавить в switch
default
который что-то сделает(например кинет ошибку) если таки лишний неведомый ключ прилетит.Maintaince
и Maintenance
. function getPropertyOfObject<T extends Record<PropertyKey, any>>(obj: T) {
const defaultKey = 'defaultKey';
function getProp<K extends keyof T>(keyOne: K): typeof defaultKey extends keyof T[K] ? T[K][typeof defaultKey] : void;
function getProp<K extends keyof T, K2 extends keyof T[K]>(keyOne: K, keyTwo: K2): T[K][K2];
function getProp(keyOne: PropertyKey, keyTwo?: PropertyKey) {
return obj?.[keyOne]?.[keyTwo ?? defaultKey];
}
return getProp;
}
{
"name": "ts",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"module": "index.js",
"license": "MIT",
"dependencies": {
"typescript": "^4.4.4"
},
"devDependencies": {
"@types/node": "^16.11.7"
}
}
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"esModuleInterop": true,
"strict": true
}
}
import cp from "child_process";
console.log(cp);