typescript 如何实现展开类型组成新的类型?

const font: Font = {
  color: "red",
  size: 16,
};
const background: Background = {
  color: "red",
  url: "",
};
const style:Style = {
  ...font,
  ...background,
};

//----------------------//

type Font = {
  color: string;
  size: number;
};
type Background = {
  color: string;
  url: string;
};
interface Style {
  // Font
  // Background
}

请问上面这个小例子里面 style 类型应该怎么写呀,查了下感觉姿势不对没查到……

阅读 1.1k
1 个回答
  1. 接口继承实现

// --- this --- 
interface Style {
}

interface Font extends Style {
  color: string;
  size: number;
}
interface Background extends Style {
  color: string;
  url: string;
}

const font: Font = {
  color: 'red',
  size: 16,
};
const background: Background = {
  color: 'red',
  url: '',
};

const style: Style = {
  ...font,
  ...background,
};
  1. 交叉类型

type Font = {
  color: string;
  size: number;
};
type Background = {
  color: string;
  url: string;
};

// ---- this -----
type Style = Font & Background;

const font: Font = {
  color: 'red',
  size: 16,
};
const background: Background = {
  color: 'red',
  url: '',
};
const style: Style = {
  ...font,
  ...background,
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏