Answer the question
In order to leave comments, you need to log in
How to make such typification?
I'm starting to learn TypeScript, and it's difficult to understand how to type such constructions.
For example, there are three methods for working with AsyncStorage in react native.
import AsyncStorage from '@react-native-community/async-storage';
//чтение данных
export async function getKey(key: string):Promise<string | null> {
try {
const value = await AsyncStorage.getItem(key);
return value
} catch (error) {
return error
}
}
//запись
export async function saveKey(key: string, value: string):Promise<void | Error> {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
return error
}
}
//удаление
export async function removeItemKey(key: string):Promise<void | Error> {
try {
await AsyncStorage.removeItem(key);
} catch (error) {
return error
}
}
type StoreTypes = {
theme: 'light' | 'dark' | null
auth: 'true' | 'false' | null
}
Answer the question
In order to leave comments, you need to log in
I'm too lazy to paint with honest promises, but the idea is
// Эта функция определена где-то в другом месте (для примера вместо AsyncStorage)
declare function someMagic(key: string): string | null;
type StoreTypes = {
theme: 'light' | 'dark' | null;
auth: 'true' | 'false' | null;
}
// Собственно декларация функции
function getKey<K extends keyof StoreTypes>(key: K): StoreTypes[K] {
return someMagic(key) as StoreTypes[K];
}
// type t = "light" | "dark" | null
const t = getKey('theme');
// type a = "true" | "false" | null
const a = getKey('auth');
// ошибка "test" не является ключом в StoreTypes
const x = getKey('test');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question