简体   繁体   English

强制执行可选类型打字稿

[英]Enforce optional type typescript

Is there a way to enforce that a function can only get called with an optional type有没有办法强制一个函数只能用可选类型调用

where Optional is defined as其中 Optional 定义为

type Optional<T> = T | undefined

I would like to define a function f so that我想定义一个函数 f 以便

declare type Foo = { foo: string }
declare var x: Optional<Foo>
declare var y: Foo

f(x) // ts typecheck ok
f(y) // ts typecheck ko 

As far as I can tell this works:据我所知这是有效的:

declare function f<T>(v:Optional<T> extends T ? T : never) : any;

Playground here游乐场在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM