简体   繁体   English

TypeScript可以参考自己的房产类型吗?

[英]Is it possible to refer self property type in TypeScript?

I want to make some logger like below code.我想制作一些像下面代码一样的记录器。

Is it possible to change unknown type to specific type?是否可以将unknown类型更改为specific类型?

type Poo = {
  prop1: 1 | 2 | 3;
  prop2: "a" | "b" | "c";
}

type Log<T> = {
  prop: keyof T;
  prev: unknown; // Todo
  cur: unknown; // Todo
}

const pooLogger: Log<Poo>[] = [];

const log: Log<Poo> = {
  prop: "prop1",
  prev: "a", // This line must cause error message like "a" is not 1 | 2 | 3
  cur: 1
}

pooLogger.push(log)

T[Log<T>["prop"]] is 1 | 2 | 3 | "a" | "b" | "c" T[Log<T>["prop"]]1 | 2 | 3 | "a" | "b" | "c" 1 | 2 | 3 | "a" | "b" | "c" 1 | 2 | 3 | "a" | "b" | "c" . 1 | 2 | 3 | "a" | "b" | "c"

You can use a conditional type to distribute the union type of T 's properties:您可以使用条件类型来分配T属性的联合类型:

type Log<T, P extends keyof T = keyof T> = P extends keyof T ?
  {prop: P; prev: T[P]; cur: unknown;} :
  never

Log<Poo> will be {prop: 'prop1', prev: 1|2|3} | {prop: 'prop2', prev: 'a'|'b'|'c'} Log<Poo>将是{prop: 'prop1', prev: 1|2|3} | {prop: 'prop2', prev: 'a'|'b'|'c'} {prop: 'prop1', prev: 1|2|3} | {prop: 'prop2', prev: 'a'|'b'|'c'}

暂无
暂无

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

相关问题 是否可以使用字符串值来引用 Typescript 中的类型 - Is it possible to use a string value to refer to a type in Typescript 在打字稿中实现带有类型参数的函数时是否可以引用类型 - is it possible to refer to a type when implementing a function with type parameters in typescript 是否可以在TypeScript中为属性名称定义类型 - Is it possible to define a type for property names in TypeScript TypeScript - 更改子项中的属性类型,是否可能? - TypeScript - Change property type in child, is it possible? 是否可以在 Typescript 的泛型类型中获取属性类型 - Is it possible to get the property type within a generic type in Typescript 打字稿:类型文字中的计算属性名称必须引用类型为文字类型或“唯一符号”的表达式 type.ts(1170) - Typescript : A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170) TypeScript 类型文字中的计算属性名称必须直接引用内置符号 - TypeScript A computed property name in a type literal must directly refer to a built-in symbol 如何在 Typescript 中引用自己的接口属性? - How to refer to own property of an interface in Typescript? 如何引用属于 TypeScript 中…其余部分的属性? - How to refer to a property which is part of the …rest in TypeScript? 如何安全地引用 Typescript 中 object 的参数化属性? - How to safely refer to a parameterised property of an object in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM