How to do this typing?

  • 0
    I am starting to learn TypeScript, and it became 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, this 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
    }
    JavaScript Grace Haley, Jul 13, 2020

  • 1 Answers
  • 0
    I'm too lazy to paint with honest promises, but the idea is this

    // Эта функция определена где-то в другом месте (для примера вместо 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 ...
    Eleanor Rosario

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!