简体   繁体   English

TypeScript defaultIfUndefined 函数类型

[英]TypeScript defaultIfUndefined function typing

I'm trying to write a simple function, which returns a defaultValue , if value === undefined .我正在尝试编写一个简单的函数,它返回一个defaultValue ,如果value === undefined

The function is super simple:功能超级简单:

const defaultIfUndefined = (value, defaultValue) => {
    return value === undefined ? defaultValue : value;
}

But the typings / type inference won't work.但是打字/类型推断将不起作用。

The function should simply remove undefined from the types.该函数应该简单地从类型中删除undefined

I tried several different things, but there's always some error.我尝试了几种不同的方法,但总是有一些错误。

1. 1.

const defaultIfUndefined = <T>(value: T, defaultValue: Exclude<T, undefined>): Exclude<T, undefined> => {
    return value === undefined ? defaultValue : value;
}

2. 2.

const defaultIfUndefined = <T, U extends Exclude<T, undefined>>(value: T, defaultValue: U): U => {
    return value === undefined ? defaultValue : value;
}

3. 3.

const defaultIfUndefined = <T, U extends T | undefined>(value: U, defaultValue: Exclude<U, undefined>): Exclude<U, undefined> => {
    return value === undefined ? defaultValue : value;
}

4. 4.

const defaultIfUndefined = <T, U extends T | undefined, V extends Exclude<U, undefined>>(value: U, defaultValue: V): V => {
    return value === undefined ? defaultValue : value;
}

The first example is working fine, as long as I return ... as any .第一个示例工作正常,只要我return ... as any

But is there some way to get this working without as any ?但是有没有办法让这个工作没有as any

-- ——

Link to TypeScript Playground 链接到 TypeScript Playground

Conditional types that contain unresolved type parameter will genrally require a type assertion.包含未解析类型参数的条件类型通常需要类型断言。 This is due to the fact that typescript does not do much math on such types, it just checks for exact matches of the conditional type.这是因为 typescript 不会对此类类型进行太多数学运算,它只是检查条件类型的精确匹配。

A solution would be to avoid conditional types:解决方案是避免条件类型:

const defaultIfUndefined = <T>(value: T | undefined | null, defaultValue: T & {}): T => {
  return value || defaultValue;
}

let a : string | null = Math.random() > 0.5 ? "" : null;
let aNotNull = defaultIfUndefined(a, "") // string 

Just a note on the T & {} .只是关于T & {}的注释。 If you change it to just T , typescript will be too aggressive in inferring a literal type, the & {} fixed that.如果将其更改为仅T ,则打字稿在推断文字类型时会过于激进, & {}修复了该问题。

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

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