掌握 TypeScript 中的文字类型:true as const 与 true

在 TypeScript 中,这两种说法之间存在显著差异:

  • clientLoader.hydrate = true 作为 const;
  • 客户端加载器.hydrate = true;
  • 仅供参考,我从 React router v7 中选择了这些示例。

    让我们通过详细的解释和例子来分析其中的区别

  • clientLoader.hydrate = true 作为 const;
  • TypeScript 中的“as const”断言是一种告诉 TypeScript 编译器将值视为其文字类型而不是一般类型的方式。

    在这种情况下,“true as const” 意味着“hydrate” 的类型将是文字“true”,而不是“boolean”。它本质上将 hydrate 的值锁定为“true”。

    例子:

    interface ClientLoader {
      hydrate: true;  // The type of hydrate is set to the literal value `true`
    }
    
    const clientLoader: ClientLoader = {
      hydrate: true as const,
    };
    
    clientLoader.hydrate = true; // This is valid
    
    // clientLoader.hydrate = false; // Error: Type 'false' is not assignable to type 'true'
  • 在上面的例子中,clientLoader.hydrate 被明确指定为 true。由于 as const 断言,您不能为 hydrate 分配除 true 之外的任何值。
  • 当您想强制某些属性的不变性时,这种类型的分配很有用。
  • 客户端加载器.hydrate = true;
  • 如果没有 `as const` 断言,TypeScript 会将 `hydrate` 的类型推断为 `boolean`。这意味着 `hydrate` 可以被赋予任何 `boolean` 值 `(true 或 false)`。

    例子:

    interface ClientLoader {
      hydrate: boolean;  // The type of hydrate is set to `boolean`
    }
    
    const clientLoader: ClientLoader = {
      hydrate: true,
    };
    
    clientLoader.hydrate = true;  // This is valid
    clientLoader.hydrate = false; // This is also valid
  • 在这种情况下,由于 hydrate 类型为布尔值,因此您可以为其分配 true 或 false。
  • 它提供了在真与假之间切换的灵活性。
  • 为什么用作 const?

  • 强制不变性:const 锁定值,使其无法更改为其他值。当你想确保特定值在整个程序中始终相同时,这特别有用。
  • 可区分联合的文字类型:使用可区分联合时,const 允许您根据文字类型创建特定情况,如下所示:
  • type Status = 'pending' | 'completed' | 'failed';
    
    const status: Status = 'pending'; // 'pending' is a valid value
    
    // status = 'in-progress'; // Error: Type '"in-progress"' is not assignable to type 'Status'
    
    // With 'as const'
    const taskStatus = 'pending' as const;
    // Now taskStatus is narrowed down to the literal type 'pending'

    结论

  • 当您想要为属性分配特定的文字值并强制该值保持固定时,请使用 const。
  • 当您想要允许属性接受不同的布尔值或不需要限制确切值时,请使用常规赋值(true,false 等)。
  • 这使得 const 成为一个有用的工具,可以在 TypeScript 代码中更精确地输入并强制执行更严格的值约束。