具有不同类型的命名属性和任意命名的索引属性的Typescript接口 [英] Typescript interface with named property and arbitrarily-named index properties of different type

查看:201
本文介绍了具有不同类型的命名属性和任意命名的索引属性的Typescript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个对象创建一个接口,该对象对于特定的命名属性具有某种类型,而对于所有其他属性则具有不同的类型.

I would like to create an interface for an object that has a certain type for a specific named property and a different type for all other properties.

如何在下面为foo编写定义?

How would I write a definition for foo below?

let foo = {
   size: 3,
   a: 'foo',
   b: 'bar',
   c: 'baz'
}

这将是我的直观方法:

interface Foo {
    size: number;
    [name: string]: string;
}

但是,TypeScript尝试将通用定义应用于特定定义并触发以下错误:

However, TypeScript tries to apply the general definition to the specific definition and triggers the following error:

error TS2411: Property 'size' of type 'number' is not assignable to string index type 'string'.

推荐答案

您可以执行以下操作(我不知道它是否可以在TS v1.5中使用):

You can do something like this (I don't know if it will work in TS v1.5):

interface Size {
    size: number;
}

interface StringMap {
    [name: string]: string;
}

type Foo = Size & StringMap;

这篇关于具有不同类型的命名属性和任意命名的索引属性的Typescript接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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