簡體   English   中英

打字稿-帶有可選參數的通用函數

[英]Typescript - Generic function with an optional parameter

我在嘗試使用可選參數鍵入通用函數時遇到了一些麻煩

type Action<TParameters = undefined> = (parameters: TParameters) => void

const A: Action = () => console.log('Hi :)') 
// Ok, as expected

const B: Action<string> = (word: string) => console.log('Hello', word)  
// Ok, as expected

const C: Action<string> = (word: number) => console.log('Hello', word)  
// Error, as expected

const D: Action<string> = () => console.log('Hello')  
// Hum, what ?!? No error ?

const E: Action<string> = (word) => console.log('Hello', word)  
// No error as expected but the type inference of `word` is `any`, why ?

自己測試

D類型檢查的原因是,忽略多余的參數經常在JavaScript中發生。 關於參數,函數f被認為的功能的亞型g只要每個參數f是具有相應的參數兼容g f中的任何其他參數都將被忽略。 請參閱https://www.typescriptlang.org/docs/handbook/type-compatibility.html中的 “比較兩個函數”

(正如@ david-sherret所指出的那樣, E工作方式與您期望的一樣,使用word: string 。)

暫無
暫無

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

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