【发布时间】:2021-01-16 11:46:14
【问题描述】:
我在我的 React Native 项目中使用 TypeScript 有一个强类型样式对象:
const styles = StyleSheet.create({
container:{
backgroundColor: 'red',
flex: 1
},
});
这与StyleSheet.create 预期任意命名键一样正常,其目标值为ViewStyle、TextStyle 和ImageStyle,定义如下:
export namespace StyleSheet {
type NamedStyles<T> = { [P in keyof T]: ViewStyle | TextStyle | ImageStyle };
/**
* Creates a StyleSheet style reference from the given object.
*/
export function create<T extends NamedStyles<T> | NamedStyles<any>>(styles: T | NamedStyles<T>): T;
[...]
}
container 是任意键,backgroundColor 在ViewStyle 中定义为具有ColorValue 类型的值,该类型定义为string | OpaqueColorValue,其中OpaqueColorValue 是唯一符号。
但是,我正在构建一个函数,我想在 ColorValue 之前以原始类型接受的任何地方提供以下类型签名:
ColorValue | { light: ColorValue, dark: ColorValue }
连同提供给我的函数的名为 light 或 dark 的参数,我将像这样使用它:
const styles = myFunction({
container:{
backgroundColor: {
light: 'red',
dark: 'blue'
},
flex: 1
},
}, 'dark');
它会选择合适的键,例如它会返回:
{
container:{
backgroundColor: 'blue' //as we picked the 'dark' key from original input
flex: 1
}
}
简单地说,我希望我的函数的输入类型能够接受StyleSheet.create 接受的任何内容,并且除此之外,无论它接受ColorValue,也接受{light: ColorValue, dark: ColorValue}。然后它选择适当的键,然后在内部调用StyleSheet.create 并返回结果。
我编写了这个函数,它可以工作,但我很难让它接受带有 IntelliSense 和 linter 中的 light/dark 键的对象(当然,不强制转换为 any 或 unknown)。
我如何做到这一点?
【问题讨论】:
-
这个问题是 React 特有的吗?如果不是,您可能希望去掉示例代码对它的依赖以构成一个minimal reproducible example,可以将其放入独立的IDE中,例如The TypeScript Playground
-
或者,如果问题是特定于 React 的,你可能想要这样标记它
-
@jcalz 不,这是 TypeScript 问题,React 只是在利用它。我会尝试提供一个 MCVE 现在更新问题。
标签: typescript dictionary strong-typing typescript4.0