关于typescript使用当中遇到的问题

1,875 阅读1分钟

1、类型检测提示信息:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'


获取值get与设置值set

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
  obj[key];

// badconst _setKeyValue = (key: string,value:any) => (obj: object) => obj[key]=value;

// betterconst _setKeyValue_ = (key: string,value:any) => (obj: Record<string, any>) => 
obj[key]=value;

// bestconst setKeyValue = <T extends object, U extends keyof T>(key: U,value:any) =>
 (obj: T) => obj[key]=value;

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

未完待续...