来自无类型对象的打字稿索引类型

时间:2018-10-28 14:52:13

标签: typescript

所以我想从react native图标模块的自动完成中获得所有图标名称。不幸的是,他们提供的类型不包括名称作为联合类型。

所以我的问题是,导入一个对象(打字稿可以识别其所有键),我如何才能将所有键作为联合类型获取。

这是我唯一想到的

import React from 'react';
import { MaterialCommunityIcons as Icon } from '@expo/vector-icons';
import { IconProps } from '@types/react-native-vector-icons/Icon'
import glyphmap from 'react-native-vector-icons/glyphmaps/MaterialCommunityIcons.json'

// create a type where I can do keyof
type MyMap<T> = {
    [ P in keyof T ]: number
};

// unnecessary? function that maps any input
// to MyMap. 
function something<T>(input: T) : MyMap<T> {
    return (input as any) as MyMap<T>
}

const result = something(glyphmap);

// finally I get all keys from glyphmap as union of string literals    
type MapKeys = keyof MyMap<typeof result>

interface Props extends IconProps {
    name: MapKeys
}

const MyIcon = (props: Props) => (
    <Icon {...props} />
)

// using here the name prop gives me all the keys as autocomplete
const Test = props => (
    <MyIcon name="access-point" />
)

如您所见,我找不到任何其他方式,如何将字形图从json文件转换为类似的内容,而无需通过无意义的函数传递

type MyMap<T> = {
    [ P in keyof T ]: number
};

那么问题又一次变得更加精确:

如何将未类型化的对象转换为MyMap,而又不将其传递给函数

1 个答案:

答案 0 :(得分:1)

更新

因此,在查看了SELECT y_inpatient_dat, pat_id, pat_enc_csn_id, LISTAGG(meas_value, '; ') WITHIN GROUP ( ORDER BY fm.recorded_time ) abnormal_HR_values FROM ( SELECT fm.y_inpatient_dat, h.pat_id, h.pat_enc_csn_id, meas_value, fm.recorded_time, SUM(length(meas_value || '; ') OVER ( ORDER BY fm.recorded_time ) running_len FROM ip_flwsht_meas fm INNER JOIN pat_enc_hsp h on fm.y_inpatient_dat = h.inpatient_data_id WHERE fm.flo_meas_id in ('8' ) and (to_number(MEAS_VALUE) <80) AND fm.recorded_time BETWEEN (SELECT start_date FROM dd) AND (SELECT end_date FROM dd) ) WHERE running_len <= 50+2 GROUP BY fm.y_inpatient_dat,h.pat_id, h.pat_enc_csn_id; (非常感谢Madara Uchiha)之后,整个事情可以转换成 one 一行代码...:D

import types

原始

哦,我发送问题后,我再次查看了一下代码,发现 type Glyphmap = typeof import('somemodule/.../file.json') 也可以直接是typeof result。所以我尝试了,并且效果很好。因此,不需要此无用的功能。

typeof glyphmap