ts类型-satifies

46 阅读1分钟

官方原文在这里

最近在看到一个新的ts语法 还没有用过 satifies,看了很多文章终不得其解

证明过程

type Color2 = {
  primary: string;
  secondary: string;
};

const theme1: Record<string, Color2> = {
  light: {
    primary: 'red',
    secondary: 'green'
  },
  dark: {
    primary: 'blue',
    secondary: 'yellow'
  }
};

/**
 * 使用 theme1.light 会失去类型提示
 * theme1.  .不出来
 * satisfies 就是为了解决这个问题
 */

const theme2 = {
  light: { primary: '#000', secondary: '#666' },
  dark: { primary: '#fff', secondary: '#ccc' }
} satisfies Record<string, Color2>;

theme2.light;

image.png

完美!

结论

我们把字面量类型 标注给一个”大类型“的时候 会失去字面量类型的推断 比如 这里的 Record<string, Color2>
light 和 dark 被定义成了 string

为了让我们的类型符合条件约束Record<string, Color2>, 又要保留我们原始的类型推断 就可以使用 satisfies