因此,我希望从react本机图标模块中获得自动完成中的所有图标名。不幸的是,它们提供的类型并不包括作为联合类型的名称。
所以我的问题是,导入一个对象(类型记录可以识别它的所有键),我如何获得所有键作为一个联合类型。
目前这是我唯一想到的
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将非类型化对象转换为
发布于 2018-10-28 14:55:22
更新
因此,在查看了import types (非常感谢Madara )之后,整个事情可以转换成一行代码.:D
type Glyphmap = typeof import('somemodule/.../file.json')原始
哦,一旦我发送了这个问题,我再次查看了代码,发现typeof result也可以是直接的typeof glyphmap。所以我试了一下,效果很好。所以不需要这个无用的功能。
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'
type MyMap<T> = {
[ P in keyof T ]: number
};
// spread keys after converting glyphmap into MyMap
type MapKeys = keyof MyMap<typeof glyphmap>
interface Props extends IconProps {
name: MapKeys
}
const MyIcon = (props: Props) => (
<Icon {...props} />
)
const Test = props => (
<MyIcon name="account" />
)https://stackoverflow.com/questions/53032779
复制相似问题