Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
枚举到对象类型的Typescript最佳实践_Typescript - Fatal编程技术网

枚举到对象类型的Typescript最佳实践

枚举到对象类型的Typescript最佳实践,typescript,Typescript,假设我们有这样一个枚举 enum CustomerType { New = 'new', Owner = 'self', Loyal = 'subscriber' } 使用此选项可以更轻松地添加检查,如 if(customer.type === CustomerType.New) 键入以枚举值作为键的对象的最佳做法是什么, 在本例中,假设我们有一个名为getCustomerType的方法,该方法将返回 { new: true, self: false,

假设我们有这样一个枚举

enum CustomerType {
   New = 'new',
   Owner = 'self',
   Loyal = 'subscriber'
}
使用此选项可以更轻松地添加检查,如

if(customer.type === CustomerType.New)
键入以枚举值作为键的对象的最佳做法是什么, 在本例中,假设我们有一个名为
getCustomerType
的方法,该方法将返回

{ 
   new: true,
   self: false,
   subscriber: false
}
另外请注意,由于设计原因,简化此操作以仅返回true密钥可能不可能:)

到目前为止,我所尝试的是

type CustomerConfig = { [key in CustomerType]: boolean }

现在让我们假设我想从这个对象得到第一个键,这是真的,我会这样做

export const getCustomer = (obj: CustomerConfig): CustomerType => {
    const customerType = Object.keys(obj).find(x => {
        // Object.keys return `string[]` instead of keyof type https://github.com/microsoft/TypeScript/issues/20853
        return obj[x as keyof CustomerConfig]
    })
    return customerType as CustomerType
}

const tempCustomer = getCustomer({
    'new': true,
    'self': false,
    'subscriber': false
})

console.log(tempCustomer === CustomerType.New)  // true
console.log(tempCustomer === CustomerType.Owner) //false


有更好的方法吗?

我建议,您可以做一些改进:

  • 数组的find函数可以返回undefined,以防它找不到任何匹配项,所以最好也添加这个类型并进行一些额外的检查
  • 正如您所说,typescript为Object.keys返回了错误的类型,因此您可以说typescript是正确的类型
export const getCustomer=(obj:CustomerConfig):CustomerType | undefined=>{
返回(对象键(obj)作为数组)
.find(x=>obj[x])
}
const tempcuster=getCustomer({
"新":对,,
“自我”:错误,
“订户”:false
})
export const getCustomer = (obj: CustomerConfig): CustomerType | undefined => {
  return (Object.keys(obj) as Array<keyof CustomerConfig>)
     .find(x => obj[x])
}

const tempCustomer = getCustomer({
    'new': true,
    'self': false,
    'subscriber': false
})