考虑一下exmaple:
type RGBA = `rgba(${number}, ${number}, ${number}, ${number})`
type Alpha = (opacity: number) => RGBA
type KeysHex = `${string}Color` | `${string}Text`
interface Data {
[color: KeysHex]: `#${string}`
[alpha: `${string}Alpha`]: Alpha
}
const foo: Data = {
criticalColor: '2' // expected error
}
const bar: Data = {
criticalColor: '#2' // ok, there is a limitation in TS
}
const baz: Data = {
criticalColorAlpha: (opacity: number) => `rgba(1, 1, 1, ${opacity})` // ok
}
const baz2: Data = {
criticalColorAlpha: (opacity: number) => `rgba(1, 1, 1, x)` // expected error
}
Playground
我注意到,如果这是一种方法,你使用Alpha
后缀,如果是十六进制 colored颜色 ,则使用Color
或Text
后缀.这就是为什么我决定在Data
界面上使用两个不同的键.
RGBA
可以使用stonger类型,但有一个限制.请看我的article和this答案.
关于六边形 colored颜色 的故事也是一样.请看this篇文章.
请提供所有场景或限制,我将尽力为您提供最安全的类型.
非常感谢.
UPDATE
[key in AdditionalKeysHex]:`#${string}`|string[];
这是错误的.只允许在映射类型中使用in
运算符.为了达到预期的行为,我认为Data
接口应该被拆分.
请参阅DataResult
类型:
type RGBA = `rgba(${number}, ${number}, ${number}, ${number})`
type Alpha = (opacity: number) => RGBA
type KeysHex = `${string}Color` | `${string}Text` | `${string}Icon` | `${string}Background`;
const arr = ['white', 'darkGrayBlue', 'secondDarkGrayBlue', 'thirdDarkGrayBlue', 'darkDullBlue', 'secondDarkDullBlue', 'lightGrayBlue', 'secondLightGrayBlue', 'thirdLightGrayBlue', 'fourthLightGrayBlue', 'fifthLighGrayBlue', 'lightGrayNavy', 'paleNavy', 'brightBlue']
type AdditionalKeysHex = 'white' | 'darkGrayBlue' | 'secondDarkGrayBlue' | 'thirdDarkGrayBlue' | 'darkDullBlue' | 'secondDarkDullBlue' | 'lightGrayBlue' | 'secondLightGrayBlue' | 'thirdLightGrayBlue' | 'fourthLightGrayBlue' | 'fifthLighGrayBlue' | 'lightGrayNavy' | 'paleNavy' | 'brightBlue';
interface IWelcome {
[color: KeysHex]: `#${string}` | string[];
[alpha: `${string}Alpha`]: Alpha;
}
type WithKey = {
[key in AdditionalKeysHex]: `#${string}` | string[];
}
interface Data {
[color: KeysHex]: `#${string}` | string[];
[alpha: `${string}Alpha`]: Alpha;
welcome: IWelcome;
}
type DataResult = WithKey & Data
const Palette: DataResult = {
primaryText: "#58585B",
secondaryText: "#39393B",
secondaryIcon: "#C8D1E8",
tertiaryText: "#8F8E94",
smallWidgetBackground: ["rgba(255,255,255,0.15)", "rgba(255,255,255,0)"],
grayColorAlpha: (opacity: number) => `rgba(200, 209, 232, ${opacity})`,
primaryTextAlpha: (opacity: number = 1) => `rgba(255, 255, 255, ${opacity})`,
welcome: {
primaryText: "#fff",
primaryTextAlpha: (opacity: number = 1) => `rgba(255, 255, 255, ${opacity})`,
secondaryText: "#C8D1E8",
loaderColor: "#fff",
},
white: '#FFFFFF',
darkGrayBlue: '#363C52',
};
Playground