如何指定 interface 的 key 为某种自定义类型?

shenxiang11
  • 428

export type Type = 'default' | 'primary' | 'info' | 'success' | 'warning' | 'error';

const style: { [type: string]: CSSProperties } = { // [type: Type] 这样会报错
    default: {
        ...baseStyle,
        color: 'rgb(51, 54, 57)',
        backgroundColor: '#0000',
    },
    primary: {
        ...baseStyle,
        color: '#FFF',
        backgroundColor: '#18a058',
    },
    info: {
        ...baseStyle,
        color: '#FFF',
        backgroundColor: '#2080f0',
    },
    success: {
        ...baseStyle,
        color: '#FFF',
        backgroundColor: '#18a058',
    },
    warning: {
        ...baseStyle,
        color: '#FFF',
        backgroundColor: '#f0a020',
    },
    error: {
        ...baseStyle,
        color: '#FFF',
        backgroundColor: '#d03050',
    },
};
回复
阅读 1.5k
2 个回答
✓ 已被采纳

{[key in Type]: CSSProperties}

type StyleType = Record<Type, CSSProperties>
//               ^^^^^^^^^^^^^^^^^^^^^^^^^^^

const style: StyleType = { ... }

传递门:TypeScript Playground Demo

宣传栏