打字稿:在类型“{“A":字符串;} [英] Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

查看:28
本文介绍了打字稿:在类型“{“A":字符串;}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些普通的 javascript 代码,它接受字符串输入,将字符串拆分为字符,然后将这些字符与对象上的键匹配.

I have some vanilla javascript code that takes a string input, splits the string into characters, and then matches those characters to a key on an object.

DNATranscriber = {
    "G":"C",
    "C": "G",
    "T": "A",
    "A": "U"
}
function toRna(sequence){
    const sequenceArray = [...sequence];
    const transcriptionArray = sequenceArray.map(character =>{
        return this.DNATranscriber[character];
    });

    return transcriptionArray.join("");
}

console.log(toRna("ACGTGGTCTTAA")); //Returns UGCACCAGAAUU

这按预期工作.我现在想将其转换为打字稿.

This works as expected. I'd now like to convert this to typescript.

class Transcriptor {
    DNATranscriber = {
       G:"C",
       C: "G",
       T: "A",
       A: "U"
    }
    toRna(sequence: string) {
        const sequenceArray = [...sequence];
        const transcriptionArray = sequenceArray.map(character =>{
            return this.DNATranscriber[character];
        });
    }
}

export default Transcriptor

但是我收到以下错误.

元素隐式具有'any'类型,因为'string'类型的表达式>不能用于索引类型'{A":string;}'.在 type >'{ "A": string; 上找不到带有类型为string"的参数的索引签名}'.ts(7053)

Element implicitly has an 'any' type because expression of type 'string' >can't be used to index type '{ "A": string; }'. No index signature with a parameter of type 'string' was found on type >'{ "A": string; }'.ts(7053)

我认为问题在于我需要我的对象键是一个字符串.但是将它们转换为字符串不起作用.

I thought that the issue was that I needed my object key to be a string. But converting them to strings didn't work.

DNATranscriber = {
       "G":"C",
       "C": "G",
       "T": "A",
       "A": "U"
    }

我对此很困惑.它说我的对象上不存在具有字符串类型的索引签名.但我确信确实如此.我做错了什么?

I'm quite confused by this. It says that no index signature with a type of string exists on my object. But I'm sure that it does. What am I doing wrong?

编辑 - 我通过给 DNATranscriber 对象一个 any 类型来解决这个问题.

Edit - I solved this by giving the DNATranscriber object a type of any.

DNATranscriber: any = {
    "G":"C",
    "C":"G",
    "T":"A",
    "A":"U"
}

推荐答案

您可以通过验证您的输入来修复错误,这是您无论如何都应该做的事情.

You can fix the errors by validating your input, which is something you should do regardless of course.

以下类型检查正确,通过类型保护验证

The following typechecks correctly, via type guarding validations

const DNATranscriber = {
    G: 'C',
    C: 'G',
    T: 'A',
    A: 'U'
};

export default class Transcriptor {
    toRna(dna: string) {
        const codons = [...dna];
        if (!isValidSequence(codons)) {
            throw Error('invalid sequence');
        }
        const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
        return transcribedRNA;
    }
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

值得一提的是,您似乎误解了将 JavaScript 转换为 TypeScript 涉及使用类.

It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.

在以下更惯用的版本中,我们利用 TypeScript 来提高清晰度并在不更改实现的情况下获得更强大的碱基对映射类型.我们使用一个 function,就像原来的一样,因为它有意义.这个很重要!将 JavaScript 转换为 TypeScript 与类无关,与静态类型有关.

In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.

const DNATranscriber = {
    G: 'C',
    C: 'G',
    T: 'A',
    A: 'U'
};

export default function toRna(dna: string) {
    const codons = [...dna];
    if (!isValidSequence(codons)) {
        throw Error('invalid sequence');
    }
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

更新:

从 TypeScript 3.7 开始,我们可以更富有表现力地编写它,使用断言签名形式化输入验证与其类型含义之间的对应关系.

Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures.

const DNATranscriber = {
    G: 'C',
    C: 'G',
    T: 'A',
    A: 'U'
} as const;

type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];

export default function toRna(dna: string): RNACodon[] {
    const codons = [...dna];
    validateSequence(codons);
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function validateSequence(values: string[]): asserts values is DNACodon[] {
    if (!values.every(isValidCodon)) {
        throw Error('invalid sequence');    
    }
}
function isValidCodon(value: string): value is DNACodon {
    return value in DNATranscriber;
}

您可以在断言签名的更多信息rel="noreferrer">TypeScript 3.7 发行说明.

You can read more about assertion signatures in the TypeScript 3.7 release notes.

这篇关于打字稿:在类型“{“A":字符串;}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆