2019年6月21日金曜日

開発環境

Programming TypeScript: Making Your JavaScript Applications Scale (Boris Cherny(著)、O'Reilly Media)のChapter 4(Functions)、Exercises(82)4の解答を求めてみる。

コード

TypeScript

// Array.fromの代替
function f(a, b) {
    let result = []
    for (let i = 0; i < a.length; i+= 1) {
        result.push(b())
    }
    return result
}
function call<T extends unknown, R>(
    f: (arg:T, value:string, ...args:T[]) => R,
    arg: T,
    s:string,
    ...args: T[]
) : R {
    return f(arg, s, ...args)
}
function fill(length: number, value: string): string[] {
    // return Array.from({length}, () => value)
    return f({length}, () => value)
}
let a = call(fill, 10, 'a')
let b = call(fill, 10, 'z')
console.log(a)
console.log(b)

入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)

$ ts-node sample4.ts 

/opt/local/lib/node_modules/ts-node/src/index.ts:243
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
sample4.ts:18:18 - error TS2339: Property 'from' does not exist on type 'ArrayConstructor'.

18     return Array.from({length}, () => value)
                    ~~~~

    at createTSError (/opt/local/lib/node_modules/ts-node/src/index.ts:243:12)
    at reportTSError (/opt/local/lib/node_modules/ts-node/src/index.ts:247:19)
    at getOutput (/opt/local/lib/node_modules/ts-node/src/index.ts:360:34)
    at Object.compile (/opt/local/lib/node_modules/ts-node/src/index.ts:393:11)
    at Module.m._compile (/opt/local/lib/node_modules/ts-node/src/index.ts:439:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/opt/local/lib/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
$ ts-node sample4.ts 
[ 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a' ]
[ 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z', 'z' ]
$ 

Array.fromを使おうとしたらエラーが発生したから、一時的に目的の同じ機能の関数fを定義して回避。

0 コメント:

コメントを投稿