簡體   English   中英

多個函數的參數類型

[英]Multiple function's argument types

嘗試編寫類型安全代碼時,我一直在解決這個問題。 我想在我的foo函數中傳遞兩個已知的精確配置變體之一,但它會出錯。 盡管如此,它似乎是類型安全的。

type Config = {
  bar: string,
} | {
  baz: string,
};

const foo = (config: Config): string => {
  if (typeof config.bar === 'undefined') {
    return config.baz;
  }

  return config.bar;
};

foo({bar: 'test'});
Property 'bar' does not exist on type 'Config'. Property 'bar' does not exist on type '{ baz: string; }'.
Property 'baz' does not exist on type 'Config'. Property 'baz' does not exist on type '{ bar: string; }'.
Property 'bar' does not exist on type 'Config'. Property 'bar' does not exist on type '{ baz: string; }'.

打字稿游樂場鏈接

幫助弄清楚如何編寫這樣的類型安全代碼,並為單個參數提供精確的配置。

您可以使用 in 運算符檢查對象上是否存在該屬性

 type Config = { bar: string, } | { baz: string, }; const foo = (config: Config): string => { if ("baz" in config) { return config.baz; } return config.bar; }; foo({bar: 'test'});

您可以執行以下操作

type Bar = { bar: string }
type Baz = { baz: string }
type Config = Bar | Baz;

const hasBaz = (config: Config): config is Baz => {
 return (config as Baz).baz !== undefined;
}

const foo = (config: Config): string => {
   return hasBaz(config) ? config.baz : config.bar
};

foo({baz: 'test'});

暫無
暫無

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

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