Skip to content

Commit

Permalink
update(web-TypeScript): implicit index signature error
Browse files Browse the repository at this point in the history
issue #105
  • Loading branch information
sabertazimi committed Aug 4, 2021
1 parent 7572010 commit 7650ce6
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions notes/web/javascript/typescriptBasicNotes.md
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,7 @@ let x: { foo: number; [x: string]: any };
x = { foo: 1, baz: 2 }; // ok, 'baz' 属性匹配于索引签名
```

当你声明一个索引签名时,所有明确的成员都必须符合索引签名
当你声明一个索引签名时,所有明确的成员都必须符合索引签名:

```ts
// ok
Expand All @@ -832,7 +832,7 @@ interface Bar {
}
```

使用交叉类型可以解决上述问题
使用交叉类型可以解决上述问题:

```ts
type FieldState = {
Expand All @@ -842,6 +842,20 @@ type FieldState = {
type FormState = { isValid: boolean } & { [fieldName: string]: FieldState };
```

**Error** `Element implicitly has an 'any' type
because expression of type 'string' can't be used to index type XXX`
can fixed with

- `Record<string, T>`.
- explicit **const** propertyName type:

```ts
// propertyName should be extends keyof T
function getProperty<T, K extends keyof T>(o: T, propertyName: K): T[K] {
return o[propertyName]; // o[propertyName] is of type T[K]
}
```

### Select Index Types

```ts
Expand Down

0 comments on commit 7650ce6

Please sign in to comment.