如何避免在 TypeScript 中添加一个因提前返回而无法访问的未定义键?

问题描述 投票:0回答:1

我正在寻找一种编写函数的方法,我不必在 TypeScript 中包含具有未定义值的键。部分是出于文体原因,部分是因为我觉得我可能误解了某些东西或错过了一种更具防御性的写作方式。

在函数中,我可能使用作为参数之一的键访问对象。如果可选参数有一个特定的键,那么就会提前返回而不涉及访问。

type MyType = 'foo' | 'bar' | 'baz'

function foo(type: MyType, objectArgument?: Record<string, number>) {
  if (type === 'baz' && objectArgument?.someProperty) {
    return {
      someKey: `hello ${someComputation(objectArgument.someProperty)}`,
      anotherKey: `goodbye ${someComputation(objectArgument.someProperty)}`
    }
  }

  const opts = {
    foo: {
      x: 'some string'
    },
    bar: {
      y: 'another string'
    }
    baz: undefined // without this baz the error the compiler errors with:
    // `Property 'baz' does not exist on type '{ foo: { x: string; }; bar: { y: string; }; }`
  }

  return opts[type]
}

一些示例调用:

foo('foo')
foo('bar')
foo('baz', { someProperty: 123 })

在上面的示例中,有没有一种方法可以在没有

opts
kvp 的情况下编写
baz: undefined
对象?

我尝试将第二个

opts
obj 包装在一个 if 语句(其余两种类型)中,并且还通过使用
return opts[type as keyof typeof opts]
成功地消除了错误但是在阅读了其他问题中的
as keyof typeof
符号之后我不确定我理解它并想确保我没有错误地欺骗编译器。

javascript typescript types javascript-objects optional-parameters
1个回答
0
投票

TypeScript 中的关键字

Exclude
可以帮助你

type MyType = 'foo' | 'bar' | 'baz'

function someComputation(n: number) { return n*2; }

function foo(type: MyType, objectArgument?: Record<string, number>) {
  if (type === 'baz' && objectArgument?.someProperty) {
    return {
      someKey: `hello ${someComputation(objectArgument.someProperty)}`,
      anotherKey: `goodbye ${someComputation(objectArgument.someProperty)}`
    }
  }

  const opts = {
    foo: {
      x: 'some string'
    },
    bar: {
      y: 'another string'
    },
     // without this baz the error the compiler errors with:
    // `Property 'baz' does not exist on type '{ foo: { x: string; }; bar: { y: string; }; }`
  }

  return opts[type as Exclude<MyType,'baz'>]
}

© www.soinside.com 2019 - 2024. All rights reserved.