从交叉路口类型中选择? (TS)
Pick from an intersection type? (TS)
我对 TS 很陌生,写了一个 pick 函数,但发现很难从交叉类型中选择:
type PaletteType = {
black: string,
white: string
}
type ColorType = {
primaryColor: string,
labelText: string,
}
type Props = {
...,
backgroundColor: keyof ColorType | keyof PaletteType // (or would keyof (ColorType & PaletteType) would be better?
}
// Some general pick funtion
function pick<T extends { [key: string]: any }, K extends keyof T>(object: T, key?: K) {
if (key) { return object[key] }
return undefined
}
pick(Colors, props.backgroundColor) // error -> black | white not assignable to Colors
我很确定我的 'solution' 有点不对:
backgroundColor: pick(Palette as typeof Palette & typeof Color, props.bg) || pick(Color as typeof Palette & typeof Color, props.bg),
添加这些声明以使代码编译:
declare const Colors: ColorType;
declare const Palette: PaletteType;
declare const props: Props;
为了使您对 pick()
的调用类型安全,您可以通过对象传播之类的方式合并 Colors
和 Palette
:
pick({ ...Colors, ...Palette }, props.backgroundColor); // okay
之所以有效,是因为 {...Colors, ...Palette}
被视为 ColorType & PaletteType
类型,其键为 keyof ColorType | keyof PaletteType
.
或者,您可以在调用 pick()
:
之前创建 user-defined type guard 以将 props.backgroundColor
缩小为 keyof ColorType
或 keyof PaletteType
const hasKey = <T extends object>(obj: T, key: keyof any): key is keyof T => key in obj;
hasKey(Colors, props.backgroundColor) ?
pick(Colors, props.backgroundColor) :
pick(Palette, props.backgroundColor); // okay
前者可能更整洁。
顺便说一下,我不确定 pick(o,k)
比 o[k]
更能给你带来什么,但我想这取决于你。
希望对您有所帮助;祝你好运!
我对 TS 很陌生,写了一个 pick 函数,但发现很难从交叉类型中选择:
type PaletteType = {
black: string,
white: string
}
type ColorType = {
primaryColor: string,
labelText: string,
}
type Props = {
...,
backgroundColor: keyof ColorType | keyof PaletteType // (or would keyof (ColorType & PaletteType) would be better?
}
// Some general pick funtion
function pick<T extends { [key: string]: any }, K extends keyof T>(object: T, key?: K) {
if (key) { return object[key] }
return undefined
}
pick(Colors, props.backgroundColor) // error -> black | white not assignable to Colors
我很确定我的 'solution' 有点不对:
backgroundColor: pick(Palette as typeof Palette & typeof Color, props.bg) || pick(Color as typeof Palette & typeof Color, props.bg),
添加这些声明以使代码编译:
declare const Colors: ColorType;
declare const Palette: PaletteType;
declare const props: Props;
为了使您对 pick()
的调用类型安全,您可以通过对象传播之类的方式合并 Colors
和 Palette
:
pick({ ...Colors, ...Palette }, props.backgroundColor); // okay
之所以有效,是因为 {...Colors, ...Palette}
被视为 ColorType & PaletteType
类型,其键为 keyof ColorType | keyof PaletteType
.
或者,您可以在调用 pick()
:
props.backgroundColor
缩小为 keyof ColorType
或 keyof PaletteType
const hasKey = <T extends object>(obj: T, key: keyof any): key is keyof T => key in obj;
hasKey(Colors, props.backgroundColor) ?
pick(Colors, props.backgroundColor) :
pick(Palette, props.backgroundColor); // okay
前者可能更整洁。
顺便说一下,我不确定 pick(o,k)
比 o[k]
更能给你带来什么,但我想这取决于你。
希望对您有所帮助;祝你好运!