【问题标题】:TypeScript: Specify a return value as well definedTypeScript:指定一个定义好的返回值
【发布时间】:2021-02-09 20:24:51
【问题描述】:

根据https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html,每个“类型”都是隐含的“类型|未定义|空”。这意味着我可以将 undefined 或 null 分配给每个变量,除非您强制执行“--strictNullChecks”。执行 strictNullChecks 会很好,但这不是我的决定,所以假设现在没有选择。

因此,与其总是检查对象的未定义变量,我想知道您是否可以编写一个函数来接收可能具有未定义或空属性的对象并返回“定义明确”的对象。这是我的意思的一个例子:

function WellDefineObject(object: SomeObjectType): SomeObjectType(*but well defined*){
    const wellDefinedObject = {
        id: (object.id == undefined || object.id == null) ? "" : object.id
    }
    return wellDefinedObject;
}

那么除了启用 strictNullChecks 之外,我的问题是否有解决方案?

【问题讨论】:

  • 关闭strictNullChecks 就是生活在狂野的一面!我从来没有关闭它,所以我必须查看它是如何工作的。您可能会在这里找到一些有用的实用程序类型:typescriptlang.org/docs/handbook/utility-types.html
  • 根据我目前的理解,老实说,当strictNullChecks 关闭时,我认为这是不可能的。您可以返回不包含 null 的类型,但该标志意味着您可以将 nullundefined 分配给任何内容,因此您返回的非空版本仍然可以有 null
  • 感谢实用程序类型的链接。使用 NonNullable 时,我仍然会遇到相同的编译器错误。我想启用 strictNullChecks 是唯一的选择。
  • 您尝试过Required<T> (Typescipt Handbook) 实用程序类型吗?

标签: typescript undefined


【解决方案1】:

我认为这不是你想要的:

type  SomeObjectType = {
   id?: string 
} 

function WellDefineObject(object: SomeObjectType): SomeObjectType{
    const wellDefinedObject = {
        id: (object.id == undefined || object.id == null) ? "" : object.id
    }
    return wellDefinedObject;
}

但是怎么样呢? :

type  SomeObjectType = {
   id: string 
} 

function WellDefineObject(object: {id? : SomeObjectType['id']}): SomeObjectType{
    const wellDefinedObject = {
        id: (object.id == undefined || object.id == null) ? "" : object.id
    }
    return wellDefinedObject;
}

两种方式:

console.log(WellDefineObject({}))
//[LOG]: {
//  "id": ""
//} 

console.log(WellDefineObject({id: "123"})) // only string fits
//[LOG]: {
//  "id": "123"  
//} 

最后你可以使用泛型:

type  SomeObjectType = {
   id: string 
} 

type NotWellDefined<T> = {
  [P in keyof T]?: T[P];
}

function WellDefineObject(object: NotWellDefined<SomeObjectType>): SomeObjectType{
    const wellDefinedObject = {
        id: (object.id == undefined || object.id == null) ? "" : object.id
    }
    return wellDefinedObject;
}

【讨论】:

    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多