簡體   English   中英

通過在 Typescript 中添加類型斷言來更改推理

[英]Change the inference by adding a type assertion in Typescript

來自: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-inference

TypeScript 不假定將1分配給以前為0的字段是錯誤的。 另一種說法是obj.counter必須具有類型number ,而不是0 ,因為類型用於確定讀取寫入行為。

這同樣適用於字符串:

 const req = { url: "https://example.com", method: "GET" }; handleRequest(req.url, req.method); // Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.

我認為“GET”是分配給 object 'req' 的變量 'method' 的默認值。 錯誤在說什么?

  1. 您可以通過在任一位置添加類型斷言來更改推理:

     // Change 1: const req = { url: "https://example.com", method: "GET" as "GET" }; // Change 2 handleRequest(req.url, req.method as "GET");

    更改 1 的意思是“我打算讓req.method始終具有文字類型"GET" ”,從而防止之后可能將"GUESS"分配給該字段。 更改 2 的意思是“由於其他原因,我知道req.method的值為"GET" ”。

在這種情況下添加類型斷言是什么意思?

這里發生了什么?

如果你 hover over req ,你會看到這個method是一個字符串。 類型已“擴大”。 你必須想辦法告訴 Typescript 不要那樣做。 其中之一是使用const

const req = { url: "https://example.com", method: "GET" } as const;

或者您可以明確地說該method是“GET”或“POST”。

const req: { url: string, method: "GET" | "POST" } = { url: "https://example.com", method: "GET" as "GET" };

或者像你一樣使用類型斷言as (我們經常被告知不要使用類型斷言,但這是一個很好的用例)

這也可以

const req = { url: "https://example.com", method: "GET" as const }; // const just on method

這個小例子將幫助您更好地理解正在發生的事情:

let num = 3 //number since you can assign something else to num
const num = 3 //3 since it's a const (not supposed to change)

創建req時,您基本上是在使用url: stringmethod: string創建 object。 這是一個與您的代碼相同的示例:

interface Request {
  url: string;
  method: string;
}
const req: Request = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);

但這樣一來,您無法確保該method是 GET 或 POST,因此如果 handleRequest 期望其中一個值,如果您傳遞一個“字符串”,它會報錯,它可能等於任何值。

一個解決方案可能是為 req 定義一個類型,例如:

interface Request {
  url: string;
  method: 'GET' | 'POST';
}

// or using 'type' if you prefer
// type Request = {
//   url: string;
//   method: 'GET' | 'POST';
// }

const req: Request = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM