V
V
vimirtv2020-10-20 14:42:27
JavaScript
vimirtv, 2020-10-20 14:42:27

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
    }
}


When calling getKey() for example, I want to ensure that only certain values ​​can be passed to it.
In my case it is theme or auth. And if it's getKey('theme') I should only get 'light' | 'dark' | null

type StoreTypes = {
    theme: 'light' | 'dark' | null
    auth: 'true' | 'false' | null
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-10-20
@vimirtv

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');

https://www.typescriptlang.org/play?#code/PTAEloQQ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question