Add a new helper type `Primitive` for JSON
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 30/100
- Tipo de issue
- Nueva funcionalidad
- Claridad
- Bastante claro
- Estado de actividad
- Estancado
- Stack tecnológico
- typescript
- Área
- compilers
Línea de trabajo
No se nombran archivos del repositorio, pruebas ni puntos de entrada. Empieza revisando el diseño del type-checker de TypeScript relevante para los tipos condicionales y mapeados recursivos, y determina después si el Primitive helper propuesto tiene un alcance aceptado y una semántica comprobable.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Search Terms
- Primitive
- JSON
Suggestion
When you encode an object to a JSON-string and decode the JSON-string to an object again, the object would be primitive. All of the methods defined in the object would be removed and its prototype would also be the primitive Object.
If the target object has a
toJSON()method, it would be converted to a pritimive of returned value from thetoJSON()method.
To express those conversions, I suggest a new helper type Primitive. I believe that providing the helper type Primitive is much better choice rather than hard-coding; enforcing programmers to implement duplicated (primitive) type definition, by themselves, considering the JSON encoding & decoding.
Below is the implementation code:
/**
* Primitify a type.
*
* If target type is an object, all methods defined in the object would be
* removed. Also, if the target type has a `toJSON()` method, its return type
* would be chosen.
*
* @typeParam T A type to be primitive
*/
export type Primitive<Instance> = value_of<Instance> extends object
? Instance extends object
? Instance extends IJsonable<infer Raw>
? value_of<Raw> extends object
? Raw extends object
? PrimitiveObject<Raw> // object would be primitified
: never // cannot be
: value_of<Raw> // atomic value
: PrimitiveObject<Instance> // object would be primitified
: never // cannot be
: value_of<Instance>;
/**
* @hidden
*/
type PrimitiveObject<Instance extends object> =
{
[P in keyof Instance]: Instance[P] extends Function
? never
: Primitive<Instance[P]>
};
/**
* @hidden
*/
type value_of<Instance> =
is_value_of<Instance, Boolean> extends true ? boolean
: is_value_of<Instance, Number> extends true ? number
: is_value_of<Instance, String> extends true ? string
: Instance;
/**
* @hidden
*/
type is_value_of<Instance, Object extends IValueOf<any>> =
Instance extends Object
? Object extends IValueOf<infer Primitive>
? Instance extends Primitive
? false
: true // not Primitive, but Object
: false // cannot be
: false;
/**
* @hidden
*/
interface IValueOf<T>
{
valueOf(): T;
}
Use Cases
interface IMember
{
id: Number;
name: string;
email: String;
mobile: string;
login_histories: LoginHistory[];
}
declare class Member
{
private id_: Number;
private name_: string;
private email_: String;
private mobile_: string;
private login_histories_: LoginHistory[];
public activate(password: string): boolean;
public isActivated(): boolean;
public toJSON(): IMember;
}
declare class LoginHistory
{
public readonly timestamp: Date;
public readonly success: Boolean;
}
function main(json: string): void
{
// Member -> Primitive<ReturnType<Member.prototype.toJSON>>
let members: Primitive<Member[]> = JSON.parse(json);
// Date -> string throw Date.toJSON()
console.log(members[0].login_histories[0].timestamp);
}
type Primitive<Member[]> = Array<{ id: number; // Number -> number name: string; email: string; // String -> string mobile: string; login_histories: Array<{ timestamp: string; // Date.toJSON(): string success: boolean; // Boolean -> boolean }>; }>;
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de microsoft/TypeScript
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
microsoft/TypeScript#64322 · 2 comentarios · 1 reacción · 2 asignados ·
-
Possible Improvement
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
microsoft/TypeScript#64278 · 1 comentario · 1 reacción ·
-
Docs
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
microsoft/TypeScript#64118 · 1 comentario ·
-
Dificultad 1/5 Menos de una hora Aptitud para principiantes 88/100
microsoft/TypeScript#64094 ·
-
Docs
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
microsoft/TypeScript#63959 · 5 comentarios ·
Todos los issues de microsoft/TypeScript
Issues similares
-
optimization optimization:agents-md-curator
Dificultad 2/5 1-3 horas Aptitud para principiantes 86/100
githubnext/gh-aw-cao#13143 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
blinklabs-io/bursa#904 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
yanet-platform/ipfw-go#129 ·
-
bug confmap/provider/googlesecretmanagerprovider needs triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
open-telemetry/opentelemetry-collector-contrib#51273 · 2 comentarios ·
-
bug: AI Gateway client filter lists "Unknown" twice when NULL and literal Unknown clients coexist Abiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 90/100