簡體   English   中英

如何以兩個 arguments 在 TypeScritp 中具有不同值的方式進行類型檢查?

[英]How to do type check in a way that two arguments have different values in TypeScritp?

考慮以下代碼:

type Country = "usa" | "uk" | "canada";
function match({c1, c2}:{c1:Country, c2: Exclude<Country, c2>}){} //This is error
match('usa', 'usa'); //I want this to be a error
match('uk', 'usa'); //and this be ok

我想強制 arguments c1 和 c2 在調用時具有不同的值。

您可以按如下方式使用 generics:

function match<C extends Country>(c1: C, c2: Exclude<Country, C>){}

不過,如果 arguments 是文字字符串,我可能只會正常工作,所以如果您打算為 arguments 使用其他東西(如變量),它可能不容易使用。

暫無
暫無

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

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