|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | +import { ESLintUtils } from '@typescript-eslint/utils'; |
| 20 | +import ts from 'typescript' |
| 21 | + |
| 22 | +const createRule = ESLintUtils.RuleCreator(name => `https://example.com/rule/${name}`) |
| 23 | + |
| 24 | +export default createRule({ |
| 25 | + name: 'dictionary-key-is-string', |
| 26 | + create(context) { |
| 27 | + return { |
| 28 | + TSTypeReference(node) { |
| 29 | + if (node.typeName.name === 'Dictionary') { |
| 30 | + const key = node.typeArguments.params[0] |
| 31 | + switch (key.type) { |
| 32 | + case 'TSTypeReference': |
| 33 | + // trace the reference to its original type definition |
| 34 | + const services = ESLintUtils.getParserServices(context) |
| 35 | + const type = services.getTypeAtLocation(key) |
| 36 | + |
| 37 | + // check that the type is a string or an enum (enum members evaluate to strings) |
| 38 | + if (type.intrinsicName !== 'string' && !(type.symbol?.flags & ts.SymbolFlags.RegularEnum)) { |
| 39 | + context.report({ node, messageId: 'stringKey' }) |
| 40 | + } |
| 41 | + break |
| 42 | + case 'TSStringKeyword': |
| 43 | + // type is string, skip |
| 44 | + break |
| 45 | + default: |
| 46 | + // unknown type! |
| 47 | + context.report({ node, messageId: 'stringKey' }) |
| 48 | + break |
| 49 | + } |
| 50 | + } |
| 51 | + }, |
| 52 | + } |
| 53 | + }, |
| 54 | + meta: { |
| 55 | + docs: { |
| 56 | + description: 'Dictionary keys must be strings', |
| 57 | + }, |
| 58 | + messages: { |
| 59 | + stringKey: "Dictionary's key must be a string" |
| 60 | + }, |
| 61 | + type: 'suggestion', |
| 62 | + }, |
| 63 | + defaultOptions: [] |
| 64 | +}) |
0 commit comments