简体   繁体   中英

TypeScript: How to conditional type in array?

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

在此处输入图像描述

在此处输入图像描述

This is my successful approach

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

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

Given a structure T , this type

type Pair<T> = {
    [K in keyof T]: [K, T[K]];
} [keyof T];

creates a Union of all possible key-value pairs (that is, ['FIRST',string] | ['SECOND',number] | etc...

Thus, the parameter of multiSet should be Array<Pair<localStorageType>>

Note that this type allows keys to be in arbitrary order and be repeated, so for example, this would be valid:

multiSet([
   ['SECOND_KEY', 'foo'],
   ['FIRST_KEY', 123],
   ['SECOND_KEY: 'bar'],
])

If you want each key to appear at most once, then pass an object (of type Partial<localStorageType> ), not an array.

I would define two different types. Then use union type to differenciate them when you use them (as params of a function for example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM