简体   繁体   English

Typescript object 类型推断为 const 但尊重某些接口

[英]Typescript object type inference as const but that respect some interface

I would like to take profit of type inference but I would like to respect some constraints let me show you我想从类型推断中获利,但我想尊重一些限制让我告诉你

Imagine I have the following function:想象一下,我有以下 function:

function getValue<T extends Record<string, number>>(object: T, key: keyof T): T[keyof T] {
  return object[key];
}

if I call it with如果我用

const Map = {
  hello: 5,
  world: 6
}

getValue(Map, "hello"); 

This work and I get correct type checking and auto-completion on "hello".这项工作,我得到了正确的类型检查和“你好”的自动完成。

But now if I want to have auto-completion when writing my map and type checking at the map definition (and not when I call the getValue function) I lost type checking and completion但是现在,如果我想在编写 map 并在 map 定义中进行类型检查时自动完成(而不是在我调用 getValue 函数时),我失去了类型检查和完成

const Map: Record<string, number> = {
  hello: 5,
  world: 6
}

getValue(Map, "titi") // No yelling

Is there any way I can use the inference but while respecting a specific interface that is more permissive?有什么方法可以使用推理,但同时尊重更宽松的特定接口?

Like saying this variable must be a number, but I want it to be infered as the value I've given.就像说这个变量必须是一个数字,但我希望它被推断为我给出的值。

const MyNumber: number = 5 as const; // Something I would like to write

when mouseover I would like MyNumber to be type 5当鼠标悬停时,我希望 MyNumber 类型为 5

Thanks谢谢

If you strongly type Map to an arbitrary Record with any key/value pair then the type checker has to allow something like "titi".如果您使用任何键/值对将Map强烈键入到任意Record ,则类型检查器必须允许类似“titi”的内容。 A best approach is to strongly type to an interface instead that nails down the shape of the object.最好的方法是对界面进行强类型输入,而不是确定 object 的形状。

function getValue<T extends IMap>(object: T, key: keyof T): T[keyof T] {
  return object[key];
}

interface IMap {
    hello: number
    world: number
}

const MapType: IMap = {
  hello: 5,
  world: 6
}

getValue(MapType, "titi"); // fails

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM