Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

TypeScript: How to conditional type in array?

$
0
0

I have difficult time to explain this, maybe pictures of my code can help

I am able to do conditional type like this

if first parameter is 'FIRST_KEY', the second parameter must be number

then if first parameter is 'SECOND_KEY', the second parameter must be a boolean

enter image description here

enter image description here

This is my successful approach

enter image description here

then i want to do the same but in an array like this

enter image description here

and i have no idea to make the typescript to work in that situation

here is my helper code and the type

i thought it gives better information using screenshots visually like this

enter image description here

Here is the code in text

helpers/local-storage.ts

import AsyncStorage from "@react-native-async-storage/async-storage"import { localStorageType } from '../references/types/local-storage'async function getItem<keyType extends keyof localStorageType>(key: keyType) {  return await AsyncStorage.getItem(key)}async function multiGet<keyType extends (keyof localStorageType)[]>(keys: keyType) {  return await AsyncStorage.multiGet(keys)}async function setItem<keyType extends keyof localStorageType, pickedlocalStorageType extends localStorageType[keyType]>(key: keyType, savedData: pickedlocalStorageType) {  await AsyncStorage.setItem(key, typeof savedData != 'string' ? JSON.stringify(savedData) : savedData)}async function multiSet()  {}multiSet([  ['FIRST_KEY', 8],  ['THIRD_KEY', 'test'],])async function removeItem<keyType extends keyof localStorageType>(key: keyType) {  await AsyncStorage.removeItem(key)}async function multiRemove<keyType extends (keyof localStorageType)[]>(keys: keyType) {  return await AsyncStorage.multiRemove(keys)}async function clear() {  await AsyncStorage.clear()}export default {  getItem,  multiGet,  setItem,  multiSet,  removeItem,  multiRemove,  clear}

types/local-storage.ts

export type localStorageType = {  FIRST_KEY: number,  SECOND_KEY: boolean,  THIRD_KEY: string}

thanks


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>