두 수의 합을 구하는 Add Type의 또 다른 구현
type Add1<N1 extends number, N2 extends number> = Length<[...NTuple<N1>, ...NTuple<N2>]>;
type Add2<N1 extends number, N2 extends number> = [...NTuple<N1>, ...NTuple<N2>] extends [...infer U]
? Length<U>
: never;
흥미롭게도 Add1은 템플릿 문자열 타입 내에서 사용할 수 없다.
즉, 이 `${Add1<1, 3>}` 타입으로 변경하여, 수를 문자로 바꾸는 활용이 불가능한데, 이는 Length 타입의 적용 시점 차이로 보인다.
아직까지는 정확한 이유는 모르겠으나 infer 키워드를 이용한 방식이 문자열 템플릿 타입 내에서 숫자를 사용할 때 더 강력한 것으로 보인다.
https://stackoverflow.com/questions/76243178/generic-type-for-adding-two-numbers
Generic type for adding two numbers
type Length<T extends any[]> = T['length']; type Push<T extends any[], V> = [...T, V]; type NTuple<N extends number, T extends any[] = []> = T['length'] extends N ? T : NTuple<N,
stackoverflow.com
스택 오버플로우에 질문을 남겼다.
https://github.com/microsoft/TypeScript/issues/53563
Type '[...T]["length"]' is not assignable to type 'string | number | bigint | boolean | null | undefined' · Issue #53563 · mic
Bug Report 🔎 Search Terms Template Literal Types 🕗 Version & Regression Information This is the behavior in every version I tried, and I reviewed the FAQ for entries about type alias preservation 💻...
github.com
https://github.com/microsoft/TypeScript/pull/53672#issuecomment-1546703126
Constraints for generic tuple types by ahejlsberg · Pull Request #53672 · microsoft/TypeScript
Fixes #53256. Fixes #53563.
github.com
만약 타입스크립트에서 버그로 태그 달아놓은 이 이슈와 동일하다면 TS 5.1에서 자동적으로 해결될 것이다.
https://github.com/kakasoo/regexp-manager/blob/main/src/new-feature.ts#L37