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


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',
    },
};
阅读 3.7k
2 个回答

{[key in Type]: CSSProperties}

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

const style: StyleType = { ... }

传递门:TypeScript Playground Demo

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进