MST

星途 面试题库

面试题:TypeScript实现CSS - in - JS类型安全方案基础

请简要描述在TypeScript中实现CSS - in - JS类型安全方案时,如何定义样式对象的类型。假设使用styled - components库,以一个简单的按钮样式为例说明。
35.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 首先安装 @types/styled - components 以获取类型声明支持。
  2. 定义按钮样式对象类型示例:
import styled from'styled - components';

// 定义按钮样式对象的类型
type ButtonStyleProps = {
  primary?: boolean;
  disabled?: boolean;
};

// 使用类型定义样式对象
const StyledButton = styled.button<ButtonStyleProps>`
  background - color: ${props => props.primary? 'blue' : 'gray'};
  color: white;
  border: none;
  padding: 10px 20px;
  border - radius: 5px;
  cursor: ${props => props.disabled? 'not - allowed' : 'pointer'};
  opacity: ${props => props.disabled? 0.5 : 1};
`;

在上述代码中:

  • 定义了 ButtonStyleProps 类型接口,用于描述按钮样式对象可能接收的属性,这里假设按钮有 primary(是否为主按钮)和 disabled(是否禁用)两个属性。
  • 在创建 StyledButton 时,将 ButtonStyleProps 作为泛型参数传递给 styled.button,这样在样式模板字符串中就可以安全地使用 props 的这些属性来设置样式,实现了类型安全的CSS - in - JS方案。