繁体   English   中英

Object 文字键值作为类型(Typescript)。 我做对了/做对了吗?

[英]Object literal key value as type (Typescript). Am I doing it right/the right thing?

我有文字 object,我希望能够将它用作 function 中的参数,例如

const SOCIAL_PROVIDER = {
  Google: 'Google',
  Facebook: 'Facebook'
}

handle(SOCIAL_PROVIDER.Google) // OK
handle(SOCIAL_PROVIDER.Twitter) // want TS to throw error
handle('Google') // want TS to throw error

然后是 function 签名类型,我让它工作的唯一方法如下

type SocialProvider = {
  Google: 'Google',
  Facebook: 'Facebook'
};

const SOCIAL_PROVIDER: SocialProvider = {
  Google: 'Google',
  Facebook: 'Facebook'
};

type handle = (value: keyof typeof SOCIAL_PROVIDER) => void

我做得对还是正确处理? 还是有更好的方法?

谢谢。

使用 TypeScript枚举

enum SocialProvider = {
  Google: 'Google',
  Facebook: 'Facebook'
};

type handle = (value: SocialProvider) => void

例子:

const func: handle = value => {
  // Do something
}

func(SocialProvider.Google);

就我个人而言,我认为仅使用您的 Providers 创建一个类型既好又简单..

例如..

type SOCIAL_PROVIDER = 'Google' | 'Facebook';
const SOCIAL_PROVIDER_HANDLE: Record<SOCIAL_PROVIDER, string> = {
  Facebook: 'FB',
  Google: 'GOOGLE'
}

function handle(provider: SOCIAL_PROVIDER) {
  console.log(SOCIAL_PROVIDER_HANDLE[provider]);  
}

handle('Google') // OK
handle('Twitter') // want TS to throw error

TS游乐场

如果你想保持干燥,另一个想法。 例如。 在上面的GoogleFacebook得到重复,你可以让 TS 为你构建类型。

例如。

const SOCIAL_PROVIDER_HANDLE = {
  Facebook: 'FB',
  Google: 'GOOGLE'
};

type SOCIAL_PROVIDER = keyof typeof SOCIAL_PROVIDER_HANDLE;

function handle(provider: SOCIAL_PROVIDER) {
  console.log(SOCIAL_PROVIDER_HANDLE[provider]);  
}

handle('Google') // OK
handle('Twitter') // want TS to throw error

暂无
暂无

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

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